CSE 1081 - Problem Solving Using Computers Lab Manual
CSE 1081 - Problem Solving Using Computers Lab Manual
COMPUTERS
LAB MANUAL
FIRST YEAR
COMMON TO ALL CORE BRANCHES
(2024 CURRICULUM)
LAB PAGE
TITLE REMARKS
NO. NO.
EVALUATION PLAN i
1 SIMPLE C PROGRAMS 1
5 1D ARRAYS 15
6 2D ARRAYS 18
7 STRINGS 20
REFERENCES 65
Course Outcomes
On completion of this laboratory course, the students will be able to:
Evaluation plan
• Internal Assessment Marks: 60%
✓ Continuous Evaluation (CE) component (for each weeks experiments):10 marks
✓ The CE will depend on punctuality, program execution, maintaining the
observation note and answering the questions in viva voce
✓ Total marks of the 12 weeks experiments reduced to marks out of 60
i
INSTRUCTIONS TO THE STUDENTS
Pre - Lab Session Instructions
1. Students should carry the Class notes, and lab record (King size note book with index)
to every lab session
2. Be in time and follow the Instructions from Lab Instructors
3. Must Sign in the log register provided
4. Make sure to occupy the allotted seat and answer the attendance
5. Adhere to the rules and maintain the decorum
ii
• The exercises for each week are divided under three sets:
o Solved exercise
o Lab exercises - to be completed during lab hours
o Additional Exercises - to be completed outside the lab or in the lab to enhance the
skill
• In case a student misses a lab class, he/she must ensure that the experiment is
completed at student’s end or in a repetition class (if available) with the permission
of the faculty concerned but credit will be given only to one day’s experiment(s).
• Questions for lab tests and examination are not necessarily limited to the questions in
the manual, but may involve some variations and/or combinations of the questions.
• A sample note preparation is given later in the manual as a model for observation.
Program:
//student name_lab1_1.c
//program to find area of circle
#include<stdio.h>
int main()
{
int radius;
float area;
printf(“Enter the radius\n”);
scanf(“%d”, &radius);
area=3.14*radius*radius;
printf("The area of circle for given radius is: %f", area);
return 0;
}
iv
LAB NO.: 1
SIMPLE C PROGRAMS
Objectives
In this lab, student will be able to:
1. Write C programs.
2. Compile and execute C programs.
3. Debug and trace the programs.
Preprocessor Directives
After the initial comments, the student should be able to see the following lines:
#include <stdio.h>
This is called a preprocessor directive. It tells the compiler to do something. Preprocessor
directives always start with a # sign. The preprocessor directive includes the information
in the file stdio.h. as part of the program. Most of the programs will almost always have
at least one include file. These header files are stored in a library that shall be learnt more
in the subsequent labs.
2
this function, there are no arguments. Arguments to functions tell the function what
objects to use in performing its task. The curly braces ({) on the next line and on the last
line (}) of the program determine the beginning and ending of the function.
Variable Declarations
The line after the opening curly brace, float centimeters, inches; is called a variable
declaration. This line tells the compiler to reserve two places in memory with adequate
size for a real number (the float keyword indicates the variable as a real number). The
memory locations will have the names inches and centimeters associated with them. The
programs often have many different variables of many different types.
EXECUTABLE STATEMENTS
Output and Input
The statements following the variable declaration up to the closing curly brace are
executable statements. The executable statements are statements that will be executed
when the program run. printf () statement tells the compiler to generate instructions that
will display information on the screen when the program run, and scanf () statement reads
information from the keyboard when the program run.
Format
Description Example
Specifiers
%d is used to print the value of integer
variable. We can also use %i to print int v;
integer value. %d and %i have same scanf(“%d”,&v);
%d
meaning printf(“value is %d”, v);
3
Assignment Statements
The statement centimeters = inches * 2.54; is an assignment statement. It calculates what
is on the right hand side of the equation (in this case inches * 2.54) and stores it in the
memory location that has the name specified on the left hand side of the equation (in this
case, centimeters). So centimeters = inches * 2.54 takes whatever was read into the
memory location inches, multiplies it by 2.54, and stores the result in centimeters. The
next statement outputs the result of the calculation.
Return Statement
The last statement of this program, return 0; returns the program control back to the
operating system. The value 0 indicates that the program ended normally. The last line of
every main function written should be return 0;
Syntax
Syntax is the way that a language must be phrased in order for it to be understandable.
The general form of a C program is given below:
// program name
// other comments like what program does and student’s name
# include <appropriate files>
int main()
{
Variable declarations;
Executable statements:
} // end main
Lab Exercises
1. Write a C program to add two integers a and b read through the keyboard. Display the
result using third variable sum
2. Write a C program to find the sum, difference, product and quotient of 2 numbers.
3. Write a C program to print the ASCII value of a character
4. Write a C program to display the size of the data type int, char, float, double, long
int and long double using size of ( ) operator.
5. Input P, N and R to compute simple and compound interest. [Hint: SI = PNR/100,
CI = P(1+R/100)N-P]
4
6. Input radius to find the volume and surface area of a sphere. [Hint: volume =
(4πr3)/3, Area=4πr2]
7. Convert the given temperature in Fahrenheit to Centigrade. [Hint: C=5/9(F-32)]
8. Write a C program to evaluate the following expression for the values a = 30,
b=10, c=5, d=15
(i ) (a + b) * c / d (ii) ((a + b) * c) / d
(iii) a + (b * c) / d (iv) (a + b) * (c / d)
Additional Exercises
1. Write a C program to convert given number of days into years , weeks and days.
2. Convert the time in seconds to hours, minutes and seconds. [Hint: 1 hr =3600 sec]
3. Write a C program for the following
a) ut + 1/2 at2 b) (ii) a2 + 2ab + b2
4. Determine how much money (in rupees) is in a piggy bank that contains
denominations of 20, 10 and 5 rupees along with 50 paisa coins. Use the following
values to test the program: 13 twenty rupee notes, 11 ten rupee notes, 7 five rupee
coins and 13 fifty paisa coins.
[Hint: 13 * 20 + 11 * 10 + 7 *5 + 0.50 *13 = Rs.411.50].
5
LAB NO.: 2
BRANCHING CONTROL STRUCTURES
Objectives:
In this lab, student will be able to do C programs using
1. simple if statement
2. if-else statement
3. switch-case statement
Introduction:
• A control structure refers to the way in which the programmer specifies the order of
execution of the instructions
Simple if statement:
If - else statement:
6
Else - if ladder:
Switch statement:
Solved Exercise
C program to compute all the roots of a quadratic equation
#include<stdio.h>
#include<math.h>
int main() {
int a,b,c;
float root1, root2, re, im, disc;
scanf("%d,%d,%d",&a,&b,&c);
disc=b*b-4*a*c;
if (disc<0) // first if condition
{
7
printf("imaginary roots\n");
re= - b / (2*a);
im = pow(fabs(disc),0.5)/(2*a);
printf("%f +i %f",re,im);
printf("%f -i %f",re,im);
//printf("%f, re",“+ i”,im);
//cout<<re<<“-i”<<im;
}
else if (disc==0){ //2nd else-if condition
printf("real & equal roots");
re=-b / (2*a);
printf("Roots are %f",re);
}
else{ /*disc > 0- otherwise part with else*/
printf("real & distinct roots");
printf("Roots are");
root1=(-b + sqrt(disc))/(2*a);
root2=(-b - sqrt(disc))/(2*a);
printf("%f and %f",root1,root2);
}
return 0;
}
Lab Exercises
With the help of various branching control constructs like if, if-else and switch case
statements,
Write C programs to do the following:
1. Check whether the given number is odd or even
2. Find the largest among given 3 numbers
3. Compute all the roots of a quadratic equation using switch case statement.
[Hint: x = (-b +/- sqrt(b2-4ac))/2a]
4. Find the smallest among three numbers using conditional operator.
8
Additional Exercises
1. Check whether the given number is zero, positive or negative, using else-if ladder.
2. Accept the number of days a member is late to return the book. Calculate and display
the fine with the appropriate message using if-else ladder. The fine is charged as per
the table below:
3. Write a program that will read the value of x and evaluate the following function
9
LAB NO.: 3
LOOPING CONTROL STRUCTURES-WHILE & DO LOOPS
Objectives:
In this lab, student will be able to:
1. Write and execute C programs using ‘while’ statement
2. Write and execute C programs using ‘do-while’ statement
3. To learn to use break and continue statements in while and do while loop statements.
Introduction:
• Iterative (repetitive) control structures are used to repeat certain statements for a
specified number of times.
• The statements are executed as long as the condition is true
• These types of control structures are also called as loop control structures
• Three kinds of loop control structures are:
o while
o do-while
o for
C looping control structures:
While loop: Do-while loop:
while (test condition) do
{ {
body of the loop body of the loop
} }
while (test condition);
Solved Exercise
[Understand the working of looping with this illustrative example for finding sum of
natural numbers up to 100 using while and do-while statements]
Using do-while
#include<stdio.h>
int main()
{
int n;
int sum;
10
sum=0; //initialize sum
n=1;
do
{
sum = sum + counter;
counter = counter +1;
} while (counter < 100);
printf(“%d”,sum);
return 0;}
Using while
#include<stdio.h>
int main( )
{
int n;
int sum;
sum=0; //initialize sum
n=1;
while (n<100)
{
sum = sum + n;
n = n +1;
}
printf(“%d”,sum);
return 0; }
Lab Exercises
Write C programs to do the following with the help of iterative (looping) control
structures such as while and do-while statements
1. Reverse a given number and check if it is a palindrome or not. (use while loop).
[Ex: 1234, reverse=4*10 3 +3 * 10 2 + 2 * 10 1 + 1 * 10 0 =4321]
2. Generate prime numbers between 2 given limits.(use while loop)
3. Check if the sum of the cubes of all digits of an inputted number equals the number
itself (Armstrong Number). (use while loop)
11
4. Write a program using do-while loop to read the numbers until -1 is encountered. Also
count the number of prime numbers and composite numbers entered by user. [Hint: 1
is neither prime nor composite]
Additional Exercises:
1. Check whether the given number is strong or not.
[Hint: Positive number whose sum of the factorial of its digits is equal to the
number itself] Ex: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145 is a strong number.
2. Write a program to demonstrate use of break and continue statements in while and
do-while loops.
12
LAB NO.: 4
LOOPING CONTROL STRUCTURES- FOR LOOPS
Objectives:
In this lab, student will be able to:
• Write and execute C programs using ‘for’ statement
• To learn to use break and continue statements in for loop statements.
Introduction:
• For loop statements are used to repeat certain statements for a specified number of
times.
• The statements are executed as long as the execution condition is true
• These types of control structures are also called as loop control structures
For loop:
for (initialization; test condition; increment/decrement)
{
body of the loop
}
Lab Exercises
With the help of for loop statements,
1. Generate the multiplication table for ‘n’ numbers up to ‘k’ terms (using nested for
loops).
[ Hint: 1 2 3 4 5 …. k
2 4 6 8 10 ….2*k
..………………..…
n……………… n*k ]
2. Generate Floyd’s triangle using natural numbers for a given limit N. (using for loops)
[Hint: Floyd’s triangle is a right angled-triangle using the natural numbers]
Ex: Input: N = 4
Output:
1
23
456
7 8 9 10
13
3. Evaluate the sine series, sin(x)= x- x3/3! + x5/5!–x7/7!+ ……… to n terms.
4. Check whether a given number is perfect or not.
[Hint: Sum of all positive divisors of a given number excluding the given number is
equal to the number] Ex: 28 = 1+ 2 + 4 + 7 + 14 = 28 is a perfect number
Additional Exercises:
1. Find out the generic root of any number.
[Hint: Generic root is the sum of digits of a number until a single digit is obtained.]
Ex: Generic root of 456 is 4 + 5 + 6 = 15 = 1+5 = 6
2. Write a program to demonstrate use of break and continue statements in for loop
14
LAB NO.: 5
1D ARRAYS
Objectives:
In this lab, student will be able to:
• Write and execute programs on 1Dimensional arrays
Introduction to 1D Arrays
1 Dimensional Array
Definition:
➢ An array is a group of related data items that share a common name.
➢ The array elements are placed in a contiguous memory location.
➢ A particular value in an array is indicated by writing an integer number called index
number or subscript in square brackets after the array name. The least value that an
index can take in array is 0.
Array Declaration:
data-type name [size];
✓ where data-type is a valid data type (like int, float,char...)
✓ name is a valid identifier
✓ size specifies how many elements the array has to contain
✓ size field is always enclosed in square brackets [ ] and takes static values.
Total size of 1D array:
The Total memory that can be allocated to 1D array is computed as:
Total size =size *(sizeof(data_type));
where, size is number of elements in 1-D array
data_type is basic data type.
Sizeof() is an unary operator which returns the size of expression
or data type in bytes.
For example, to represent a set of 5 numbers by an array variable Arr, the declaration the
variable Arr is
int Arr[5];
15
Solved Exercise
Sample Program to read n elements into a 1D array and print it:
#include<stdio.h>
int main()
{
int a[10], i, n;
printf(“enter no of elements");
scanf(“%d”,&n);
printf(“enter n values\n");
for(i=0;i<n;i++) // input 1D array
scanf(“%d”,&a[i]);
printf(“\nNumbers entered are:\n”);
for(i=0;i<n;i++) // output 1D array
printf(“%d”,a[i]);
return 0;
}
Output:
Enter no. of elements
3
Enter n values
9
11
13
17
LAB NO.: 6
2D ARRAYS
Objectives:
In this lab, student will be able to:
• Write and execute programs on 2D dimensional arrays
For example
int marks[5][3];
float matrix[3][3];
char page[25][80];
• The first example tells that marks is a 2-D array of 5 rows and 3 columns.
• The second example tells that matrix is a 2-D array of 3 rows and 3 columns.
• Similarly, the third example tells that page is a 2-D array of 25 rows and 80
columns.
Solved Exercise:
#include<stdio.h>
int main()
{
int i,j,m,n,a[100][100];
printf(“enter dimension of matrix");
scanf(“%d %d”,&m,&n);
printf(“enter the elements");
for(i=0;i<m;i++) // input 2D array using 2 for loops
{
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
18
}
for(i=0;i<m;i++) // output 2D array with 2 for loops
{
for(j=0;j<n;j++)
printf("%d\t”,a[i][j]);
printf(“\n”);
}
return 0;
}
Lab Exercises
With the knowledge of 2D arrays,
Write C programs to do the following:
1. Find whether a given matrix is symmetric or not. [Hint: A = AT]
2. Find the trace and norm of a given square matrix.
[Hint: Trace= sum of principal diagonal elements
Norm= SQRT (sum of squares of the individual elements of an array)]
3. Perform matrix multiplication.
4. To interchange the primary and secondary diagonal elements in the given Matrix.
19
LAB NO.: 7
STRINGS
Objectives:
In this lab, student will be able to:
1. Declare, initialize, read and write a string
2. Write C programs with and without string handling functions to manipulate the given
string
Introduction
• A string is an array of characters.
• Any group of characters (except double quote sign) defined between double
quotations is a constant string.
• Character strings are often used to build meaningful and readable programs.
Declaration
Syntax: char string_name[size];
• The size determines the number of characters in the string_name.
Solved Exercise
Program to read and display a string
#include<stdio.h>
int main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
printf(“Enter a string: ”);
scanf(“%s”,str);
20
//put string in str
Printf(“You entered: %s\n” str); //display string from str
return 0;}
Lab Exercises
With the brief introduction and knowledge on strings, write C programs without using
STRING-HANDLING functions for the following:
1. Count the number of words in a sentence.
2. Input a string and toggle the case of every character in the input string.
Ex: INPUT: aBcDe
OUTPUT: AbCdE
3. Check whether the given string is a palindrome or not.
4. Arrange ‘n’ names in alphabetical order (hint: use string handling function-strcpy)
5. Delete a word from the given sentence.
Ex: INPUT: I AM STUDYING IN MIT
TO BE DELETED: STUDYING
OUTPUT: I AM IN MIT
Additional Exercises
1. Search for a given substring in the main string.
2. Delete all repeated words in the given String.
3. Read a string representing a password character by character and mask every
character in the input with ‘*’.
4. Write a C program using 1D array to read an alphanumeric string (Eg. abc14fg67)
and count the number of characters and digits in the given string and display the sum
of all the digits.
21
LAB NO.: 8
MODULAR PROGRAMMING -FUNCTIONS
Objectives:
In this lab, student will be able to:
1. Understand modularization and its importance
2. Define and invoke a function
3. Analyze the flow of control in a program involving function call
4. Write programs using functions
Introduction
• A function is a set of instructions to carry out a particular task.
• Using functions programs can be structured in a more modular way.
22
Solved Exercise
1. Program for explaining concept of multiple functions
#include<stdio.h>
void First (void){
printf(“I am now inside function First\n”);
}
void Second (void){
printf(“I am now inside function Second\n”);
First();
printf(“Back to Second\n”);
}
int main (){
printf(“I am starting in function main\n”);
First ();
printf(“Back to main function \n”);
Second ();
printf(“Back to main function \n”);
return 0;
}
Lab Exercises
With the knowledge of modularization, function definition, function call etc., write C
programs which implement simple functions.
Write C programs as specified below:
1. Write a function Fact to find the factorial of a given number. Using this function,
compute NCR in the main function.
2. Write a function Largest to find the maximum of a given list of numbers. Also write
a main program to read N numbers and find the largest among them using this
function.
3. Write a function IsPalin to check whether the given string is a palindrome or not.
Write a main function to test this function.
4. Write a function CornerSum which takes as a parameter, no. of rows and no. of
columns of a matrix and returns the sum of the elements in the four corners of the
matrix. Write a main function to test the function.
23
Additional Exercises
1. Write a function IsPrime to check whether the given number is prime or not.
Using this function, generate first N prime numbers in the main function.
2. Write a function array_sum to find the sum of ‘n’ numbers in an array. Write a
main program to read ‘n’ numbers and use array_sum function to find the sum of
‘n’ numbers.
3. Write a function toggle to toggle the case of each character in a sentence. Write a
main program to read a sentence and use toggle function to change the case of each
character in the given sentence.
24
LAB NO.: 9
MATLAB INTRODUCTION & PROGRAMMING
MATLAB is an interactive system whose basic data element is an array that does not
require dimensioning. This allows you to solve many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it would
take to write a program in a scalar non-interactive language such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally written to
provide easy access to matrix software developed by the LINPACK and EISPACK
projects. Today, MATLAB engines incorporate the LAPACK and BLAS libraries,
embedding the state of the art in software for matrix computation.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses
in mathematics, engineering, and science. In industry, MATLAB is the tool of choice for
high-productivity research, development, and analysis.
26
4. Graphics: MATLAB has extensive facilities for displaying vectors and matrices as
graphs, as well as annotating and printing these graphs. It includes high-level
functions for two-dimensional and three-dimensional data visualization, image
processing, animation, and presentation graphics. It also includes low-level
functions that allow you to fully customize the appearance of graphics as well as to
build complete graphical user interfaces on your MATLAB applications.
5. The MATLAB External Interfaces/API: This is a library that allows you to write
C and Fortran programs that interact with MATLAB. It includes facilities for calling
routines from MATLAB (dynamic linking), calling MATLAB as a computational
engine, and for reading and writing MAT-files.
Features
• Basic data element: matrix
- Auto dimensioning
- eliminates data type declarations
- ease of programming
- Operator overloading
- Case sensitive
• Advanced visualisation
- 2D and 3D
- Simple programming
- colour graphics
• Open environment
Desktop basics
When you start MATLAB®, the desktop appears in its default layout.
27
The desktop includes these panels:
Current Folder — Access your files.
Command Window — Enter commands at the command line, indicated by the prompt
(>>).
Workspace — Explore data that you create or import from files.
As you work in MATLAB, you issue commands that create variables and call functions.
For example, create a variable named a by typing this statement at the command line:
a=1
MATLAB adds variable a to the workspace and displays the result in the Command
Window.
a=
1
Create a few more variables.
b=2
b=
2
c=a+b
c=
3
d = cos(a)
d=
0.5403
When you do not specify an output variable, MATLAB uses the variable ans, short
for answer, to store the results of your calculation.
sin(a)
ans =
0.8415
28
If you end a statement with a semicolon, MATLAB performs the computation, but
suppresses the display of output in the Command Window.
e = a*b;
You can recall previous commands by pressing the up- and down-arrow keys, ↑ and ↓.
Press the arrow keys either at an empty command line or after you type the first few
characters of a command. For example, to recall the command b = 2, type b, and then
press the up-arrow key.
1 2 3 4
1 2 3
4 5 6
7 8 10
Another way to create a matrix is to use a function, such as ones, zeros, or rand. For
example, create a 5-by-1 column vector of zeros.
z = zeros(5,1)
29
z = 5×1
0
0
0
0
0
11 12 13
14 15 16
17 18 20
sin(a)
ans = 3×3
1 4 7
2 5 8
3 6 10
30
You can perform standard matrix multiplication, which computes the inner products
between rows and columns, using the * operator. For example, confirm that a matrix
times its inverse returns the identity matrix:
p = a*inv(a)
p = 3×3
1.0000 0 -0.0000
0 1.0000 0
0 0 1.0000
Notice that p is not a matrix of integer values. MATLAB stores numbers as
floating-point values, and arithmetic operations are sensitive to small differences
between the actual value and its floating-point representation. You can display more
decimal digits using the format command:
format long
p = a*inv(a)
p = 3×3
1.000000000000000 0 -0.000000000000000
0 1.000000000000000 0
0 0 0.999999999999998
Reset the display to the shorter format using
format short
format affects only the display of numbers, not the way MATLAB computes or saves
them.
To perform element-wise multiplication rather than matrix multiplication, use
the .* operator:
p = a.*a
p = 3×3
1 4 9
16 25 36
49 64 100
31
The matrix operators for multiplication, division, and power each have a corresponding
array operator that operates element-wise. For example, raise each element of a to the
third power:
a.^3
ans = 3×3
1 8 27
64 125 216
343 512 1000
Concatenation
Concatenation is the process of joining arrays to make larger ones. In fact, you
made your first array by concatenating its individual elements. The pair of square
brackets [] is the concatenation operator.
A = [a,a]
A = 3×6
1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
1 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 10
32
Complex Numbers
Complex numbers have both real and imaginary parts, where the imaginary unit is the
square root of -1.
sqrt(-1)
ans = 0.0000 + 1.0000i
To represent the imaginary part of complex numbers, use either i or j .
c = [3+4i, 4+3j; -i, 10j]
c = 2×2 complex
33
Control Flow Statements
• for loop : for k = 1:m
.....
end
• while loop : while condition
.....
end
• if statement : if condition1
.....
else if condition2
.....
else
.....
end
Array indexing
Every variable in MATLAB® is an array that can hold many numbers. When you want
to access selected elements of an array, use indexing.
For example, consider the 4-by-4 magic square A:
A = magic(4)
A = 4×4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
There are two ways to refer to a particular element in an array. The most common way is
to specify row and column subscripts, such as
A(4,2)
ans = 14
34
Less common, but sometimes useful, is to use a single subscript that traverses down each
column in order:
A(8)
ans = 14
Using a single subscript to refer to a particular element in an array is called linear
indexing.
If you try to refer to elements outside an array on the right side of an assignment statement,
MATLAB throws an error.
test = A(4,5)
Index exceeds matrix dimensions.
However, on the left side of an assignment statement, you can specify elements outside
the current dimensions. The size of the array increases to accommodate the newcomers.
A(4,5) = 17
A = 4×5
16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17
To refer to multiple elements of an array, use the colon operator, which allows you to
specify a range of the form start:end. For example, list the elements in the first three rows
and the second column of A:
A(1:3,2)
ans = 3×1
2
11
7
The colon alone, without start or end values, specifies all of the elements in that
dimension. For example, select all the columns in the third row of A:
A(3,:)
ans = 1×5
9 7 6 12 0
35
The colon operator also allows you to create an equally spaced vector of values using the
more general form start:step:end.
B = 0:10:100
B = 1×11
0 10 20 30 40 50 60 70 80 90 100
If you omit the middle step, as in start:end, MATLAB uses the default step value of 1.
Workspace variables
The workspace contains variables that you create within or import into MATLAB® from
data files or other programs. For example, these statements create variables A and B in
the workspace.
A = magic(4);
B = rand(3,5,2);
You can view the contents of the workspace using whos.
whos
Name Size Bytes Class Attributes
Workspace variables do not persist after you exit MATLAB. Save your data for later
use with the save command,
save myfile.mat
Saving preserves the workspace in your current working folder in a compressed file
with a .mat extension, called a MAT-file.
36
To clear all the variables from the workspace, use the clear command.
Restore data from a MAT-file into the workspace using load.
load myfile.mat
Some useful commands
who whos clc clf clear load save pause help pwd ls dir
37
Determinant of a matrix
>> A_det = det(A)
Inverse of a matrix
>> A_inv = inv(A)
Matrix multiplication
>> C = A * A_trans
Array multiplication
>> c = a .* b % a.*b denotes element-by-element multiplication.
% vectors a and b must have the same dimensions.
The online help system is accessible using the help command. Help is available for
functions e.g. help inv and for Punctuation help punct. A useful command to get started
is intro, which covers the basic concepts in MATLAB language. Demonstration programs
can be started with the command demo. Demos can also be invoked from the Help Menu
at the top of the window.
>>lookfor inverse
The function lookfor becomes useful when one is not sure of the MATLAB function
name.
>>clc %clear command window
>> save session1 % workspace variables stored in session1.mat
>>save myfile.dat a b -ascii % saves a,b in myfile.dat in ascii format
>>clear % clear workspace
>>who
>>load session1 % To load variables to workspace
>>who
38
More Matrix manipulations
A = [1 3 5;2 4 4; 0 0 3]
B = [1 0 1; 2 2 2; 3 3 3]
Sample Solution a:
(using command line editor)
>> Z = [170 -100 -30; -100 160 -30; -30 -30 70];
>> v = [0; 0; 10];
>>i = inv(Z) * v
Typing ex_1b at the command prompt will run the script file, and all the 7 commands
will be executed sequentially. The script file can also be executed from the Run icon in
the MATLAB Editor.
Results:
i = 0.1073
0.1114
0.2366
40
Function File
A function file is also an m-file, just like a script file, except it has a function definition
line at the top that defines the input and output explicitly.
function<output_list> = fname <input_list>
Save the file as fname.m The filename will become the name of the new command for
MATLAB. Variables inside a function are local. Use global declaration to share
variables.
r = abs(x);
theta = angle(x)*180/pi;
MATLAB functions operate on arrays just as easily as they operate on scalars. For
example, if x is an array, then cos(x) returns an array of the same size as x containing the
cosine of each element of x.
41
Avoiding loops - Since MATLAB is an interpreted language, certain common
programming habits are intrinsically inefficient. The primary one is the use of for loops
to perform simple operations over an entire matrix or vector. Wherever possible, you
should try to find a vector function that will accomplish the desired result, rather than
writing loops.
For example, to sum all the elements of a matrix
By using for loops:
[Nrows, Ncols]=size(x);
xsum=0.0;
for m=1:Nrows
for n=1:Ncols
xsum=xsum+x(m,n);
end;
end;
Vectorised code:
xsum=sum(sum(x));
Repeating rows or columns - If the matrix has all same values use ones(M,N) and
zeros(M,N). To replicate a column vector x to create a matrix that has identical columns,
x=(12:-2:0)'; X= x*ones(1,11).
Experience has shown that MATLAB is easy to learn and use. You can learn a lot by
exploring the Help & Demos provided and trying things out. One way to get started is by
viewing and executing script files provided with the software. Don’t try to learn
everything at once. Just get going and as you need new capabilities find them, or, if
necessary, make them yourself.
42
LAB NO.: 10
MODULAR PROGRAMMING – RECURSIVE FUNCTIONS,
STRUCTURES, POINTERS
Objectives:
In this lab, student will be able to:
1. To Learn the concept of recursion and to write recursive functions
2. Declare and initialize pointer variable
3. Write basic operations and programs using structures
4. Access a variable through its pointer
Introduction:
• A recursive function is a function that invokes/calls itself directly or indirectly.
• A Pointer is a memory location or a variable which stores the address of another
variable in memory
• A structure in the C programming language (and many derivatives) is a composite
data type (or record) declaration that defines a physically grouped list of variables to
be placed under one name in a block of memory.
• A file is a place on disc where group of related data is stored.
43
Solved Exercise
Program to explain the concept of recursive functions
#include<stdio.h>
long factorial (long a) {
if (a ==0) //base case
return (1);
return (a * factorial (a-1));
}
int main () {
long number;
printf(“Please type a number: ");
scanf(“%d”,&number);
printf("%d factorial is %ld",number, factorial (number));
return 0;
}
Solved Exercise:
#include<stdio.h>
int main()
{
int var1 = 11; //two integer variables
int var2 = 22;
int *ptr; //pointer to integer
ptr = &var1; //pointer points to var1
44
printf("%d",*ptr); //print contents of pointer (11)
ptr = &var2; //pointer points to var2
printf("%d",*ptr); //print contents of pointer (22)
return 0;
}
struct student
{
int rollno, age;
char name[20];
} s1, s2, s3;
Initialisation :
int main( ){
struct
{
int rollno;
int age;
} stud={20, 21};
…
…
return 0;
}
Solved Exercise:
#include<stdio.h>
struct Book{ //Structure Definition
char title[20];
char author[15];
int pages;
float price;
};
45
int main( ){
struct Book b[10];
int i,j;
printf("Input values");
for (i=0;i<10;i++){
scanf("%s %s %d %f",b[i].title,b[i].author,&b[i].pages,&b[i].price);
}
for (j=0;j<10;j++){
printf("title %s\n author %s\n pages %d\n
price%f\n",b[j].title,b[j].author,b[j].pages,b[j].price);
}
return 0;
}
Lab Exercises
2. Write a recursive function FIB to generate nth Fibonacci term. Write a main program
to print first N Fibonacci terms using function FIB.
[Hint: Fibonacci series is 0, 1, 1, 2, 3, 5, 8 ...]
3. Find the maximum number in the input integer array using pointers.
4. Create a student record with name, rollno, marks of 3 subjects (m1, m2, m3). Compute
the average of marks for 3 students and display the names of the students in ascending
order of their average marks.
Additional Exercises
1. Find the length of the string using pointers.
2. Write a program to multiply two numbers using a recursive function.
[Hint: Multiplication using repeated addition]
46
3. Write a C program to find the frequency of a word in an inputted string using
pointers.
4. Create an employee record with emp-no, name, age, date-of-joining (year), and
salary. If there is 20% hike on salary per annum, compute the retirement year of
each employee and the salary at that time. [standard age of retirement is 55]
47
LAB NO.: 11
Illustration
Plot a symbolic expression or function in polar coordinates (radius) and (polar angle)
by using ezpolar. By default, ezpolar plots a symbolic expression or function over the
interval .
Plot the symbolic expression in polar coordinates.
>>syms t
>>ezpolar(sin(6*t))
2D Plot of
48
Exercise – 1
✓ Plot the symbolic expression by using fplot. By default, fplot uses the range
Code view
% Button pushed function: SINWaveButton
function SINWaveButtonPushed(app, event)
x=linspace(0,4*pi,100);
y=sin(x);
plot(y)
end
50
Web sharing Matlab App
Web App
Standalone App
51
Exercise – 2
Create a following GUI App to find and display the Simple and Compound interest for
the given principle, duration and rate in respective text (numeric) fields on click of push
button. Refer below GUI for your representation.
Exercise – 3
Create a GUI app find below using appropriate controls.
53
Note:
• Click on the runtime output to access controls like “grid”, title”, “x label”, “y
label” etc on “Figure” to add code and update
• Click on save as control in Home tab to save the desired document in PDF.
Exercise – 4
Use Matlab Live Editor illustrative procedure to generate PDF documents of following
assignments.
• Plot of parametric space curve x (t) = t, y (t) = t2 , z (t) = t3; 0 ≤ t ≤ 1, using plot3
and give suitable labels through “figure” tab and update the code in program
code.
• 2D plot for the function, x=t, y=e t, 0 ≤ t ≤ 2π using semilogy.
• Both 3D-mesh and 3D-colored surface in the same Figure window using
subplot
[Hint: subplot (221), mesh(Z)]
54
LAB NO.: 12
Objectives:
Analysis of simple systems using SIMULINK
55
Simulating this model integrates a brief pulse twice to get a ramp. The results display in
a Scope window. The input pulse represents a press of the gas pedal — 1 when the pedal
is pressed and 0 when it is not. The output ramp is the increasing distance from the starting
point.
Open New Model
Use the Simulink Editor to build your models.
1. Start MATLAB®. From the MATLAB tool-strip, click the Simulink button
56
2. Click the Blank Model template.
3. From the File menu, select Save as. In the File name text box, enter a name for your
model, For example, simple model. Click Save. The model is saved with the file
extension.slx.
Open Simulink Library Browser
Simulink provides a set of block libraries, organized by functionality in the Library
Browser. The following libraries are common to most workflows:
• Continuous — Blocks for systems with continuous states
• Discrete — Blocks for systems with discrete states
• Math Operations — Blocks that implement algebraic and logical equations
• Sinks — Blocks that store and show the signals that connect to them
• Sources — Blocks that generate the signal values that drive the model
• From the Simulink Editor toolbar, click the Library Browser button
57
• Set the Library Browser to stay on top of the other desktop windows. On the Library
Browser toolbar, select the Stay on top button
To browse through the block libraries, select a category and then a functional area in the
left pane. To search all of the available block libraries, enter a search term.
For example, find the Pulse Generator block. In the search box on the browser toolbar,
enter pulse, and then press the Enter key. Simulink searches the libraries for blocks
with pulse in their name or description, and then displays the blocks.
58
Get detailed information about a block. Right-click a block and then select Help for the
Pulse Generator block. The Help browser opens with the reference page for the block.
Blocks typically have several parameters. You can access all parameters by double-
clicking the block.
Add Blocks to a Model
To start building the model, browse the library and add the blocks.
• From the Sources library, drag the Pulse Generator block to the Simulink Editor. A
copy of the Pulse Generator block appears in your model with a text box for the value
of the Amplitude parameter. Enter 1.
59
• Arrange the blocks as follows by clicking and dragging each block. To resize a block,
click and drag a corner.
Connect Blocks
Connect the blocks by creating lines between output ports and input ports.
4. Click the output port on the right side of the Pulse Generator block.
The output port and all input ports suitable for a connection get highlighted.
60
5. Click the input port of the Gain block.
Simulink connects the blocks with a line and an arrow indicating the direction of
signal flow.
6. Connect the output port of the Gain block to the input port on the Integrator, Second
Order block.
7. Connect the two outputs of the Integrator, Second Order block to the
two Outport blocks.
8. Save your model. Select File > Save and provide a name.
61
Add Signal Viewer
To view simulation results, connect the first output to a Signal Viewer.
Access the context menu by right clicking the signal. Select Create & Connect Viewer
> Simulink > Scope. A viewer icon appears on the signal and a scope window opens.
You can open the scope at any time by double-clicking the icon.
Run Simulation
After you define the configuration parameters, you are ready to simulate your model.
• On the model window, set the simulation stop time by changing the value at the
toolbar.
The default stop time of 10.0 is appropriate for this model. This time value has no
unit. Time unit in Simulink depends on how the equations are constructed. This
example simulates the simplified motion of a car for 10 seconds — other models could
have time units in milliseconds or years.
62
Exercises:
Verify the following Electrical circuit output using Simulink
1. An RC series circuit with R = 1, & C = 10mF is connected to a dc source of 10V
through a switch. Plot the applied voltage, current and the capacitor voltage for time,
0 t 2s, if the switch is closed at t = 1s & the circuit elements are initially relaxed.
Circuit
Taking
The above equation may be re-written as
63
Simulink model describing the above block diagram is
Equation
64
Block diagram
Additional exercises:
REFERENCES
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming language (2e),
Pearson Education, 2015.
2. Deital.P. J and Deitel.H.M, C: How to program (7e), Pearson Education, 2010.
3. Balagurusamy.E, Computing fundamentals and C programming (1e), MC GRAW
HILL INDIA, 2017.
4. Delores Etter, Introduction to MATLAB, Pearson Education India, 2019.
5. Stormy Attaway, Matlab: A practical Introduction to Programming and Problem Solving
(4e), Butterworth-Heinemann, Elsevier, 2017.
65
C LANGUAGE QUICK REFERENCE
PREPROCESSOR
// Comment to end of line
/* Multi-line comment */
#include <stdio.h> // Insert standard header file
#include "myfile.h" // Insert file in current directory
#define X some text // Replace X with some text
#define F(a,b) a+b // Replace F(1,2) with 1+2
#define X \
some text // Line continuation
#undef X // Remove definition
#if defined(X) // Condional compilation (#ifdef X)
#else // Optional (#ifndef X or #if !defined(X))
#endif // Required after #if, #ifdef
LITERALS
255, 0377, 0xff // Integers (decimal, octal, hex)
2147463647L, 0x7fffffffl // Long (32-bit) integers
123.0, 1.23e2 // double (real) numbers
‘a’, ‘\141’, ‘\x61’ // Character (literal, octal, hex)
‘\n’, ‘\\’, ‘\’’, ‘\”’, // Newline, backslash, single quote, double quote
“string\n” // Array of characters ending with newline and \0
“hello” “world” // Concatenated strings
true, false // bool constants 1 and 0
DECLARATIONS
int x; // Declare x to be an integer (value undefined)
int x=255; // Declare and initialize x to 255
short s; long 1; // Usually 16 or 32 bit integer (int may be either)
char c= ‘a’; // Usually 8 bit character
unsigned char u=255; signed char m=-1; // char might be either
unsigned long x=0xffffffffL; // short, int, long are signed
float f; double d; // Single or double precision real (never unsigned)
66
bool b=true; // true or false, may also use int (1 or 0)
int a, b, c; // Multiple declarations
int a[10]; // Array of 10 ints (a[0] through a[9])
int a[]={0,1,2}; // Initialized array (or a[3]={0,1,2}; )
int a[2][3]={{1,2,3},{4,5,6}; // Array of array of ints
char s[]= “hello”; // String (6 elements including ‘\0’)
int* p; // p is a pointer to (address of) int
char* s= “hello”; // s points to unnamed array containing "hello"
void* p=NULL; // Address of untyped memory (NULL is 0)
int& r=x; // r is a reference to (alias of) int x
enum weekend {SAT, SUN}; // weekend is a type with values SAT and SUN
enum weekend day; // day is a variable of type weekend
enum weekend {SAT=0,SUN=1}; // Explicit representation as int
enum {SAT,SUN} day; // Anonymous enum
typedef String char*; // String s; means char* s;
const int c=3; // Constants must be initialized, cannot assign
const int* p=a; // Contents of p (elements of a) are constant
int* const p=a; // p (but not contents) are constant
const int* const p=a; // Both p and its contents are constant
const int& cr=x; // cr cannot be assigned to change x
STORAGE CLASSES
int x; // Auto (memory exists only while in scope)
static int x; // Global lifetime even if local scope
extern int x; // Information only, declared elsewhere
STATEMENTS
x=y; // Every expression is a statement
int x; // Declarations are statements
; // Empty statement
{ // A block is a single statement
int x; // Scope of x is from declaration to end of block
a; // In C, declarations must precede statements
}
if (x) a; // If x is true (not 0), evaluate a
67
else if (y) b; // If not x and y (optional, may be repeated)
else c; // If not x and not y (optional)
while (x) a; // Repeat 0 or more times while x is true
for (x; y; z) a; // Equivalent to: x; while(y) {a; z;}
do a; while (x); // Equivalent to: a; while(x) a;
switch (x) { // x must be int
case X1: a; // If x == X1 (must be a const), jump here
case X2: b; // Else if x == X2, jump here
default: c; // Else jump here (optional)
}
break; // Jump out of while, do, for loop, or switch
continue; // Jump to bottom of while, do, or for loop
return x; // Return x from function to caller
try { a; }
catch (T t) { b; } // If a throws T, then jump here
catch (...) { c; } // If a throws something else, jump here
FUNCTIONS
int f(int x, int); // f is a function taking 2 ints and returning int
void f(); // f is a procedure taking no arguments
void f(int a=0); // f() is equivalent to f(0)
f(); // Default return type is int
inline f(); // Optimize for speed
f( ) { statements; } // Function definition (must be global)
Function parameters and return values may be of any type. A function must either be
declared or defined before it is used. It may be declared first and defined later. Every
program consists of a set of global variable declarations and a set of function definitions
(possibly in separate files), one of which must be:
int main() { statements... } or
int main(int argc, char* argv[]) { statements... }
argv is an array of argc strings from the command line. By convention, main returns
status 0 if successful, 1 or higher for errors.
68
EXPRESSIONS
Operators are grouped by precedence, highest first. Unary operators and assignment
evaluate right to left. All others are left to right. Precedence does not affect order of
evaluation which is undefined. There are no runtime checks for arrays out of bounds,
invalid pointers etc.
::X // Global name X
t.x // Member x of struct or class t
p→x // Member x of struct or class pointed to by p
a[i] // i’th element of array a
f(x, y) // Call to function f with arguments x and y
x++ // Add 1 to x, evaluates to original x (postfix)
x-- // Subtract 1 from x, evaluates to original x
sizeof x // Number of bytes used to represent object x
sizeof(T) // Number of bytes to represent type T
++x // Add 1 to x, evaluates to new value (prefix)
--x // Subtract 1 from x, evaluates to new value
~x // Bitwise complement of x
!x // true if x is 0, else false (1 or 0 in C)
-x // Unary minus
+x // Unary plus (default)
&x // Address of x
*p // Contents of address p (*&x equals x)
x*y // Multiply
x/y // Divide (integers round toward 0)
x%y // Modulo (result has sign of x)
x+y // Add, or &x[y]
x–y // Subtract, or number of elements from *x to *y
x << y // x shifted y bits to left (x * pow(2, y))
x >> y // x shifted y bits to right (x / pow(2, y))
x<y // Less than
x <= y // Less than or equal to
x>y // Greater than
x >= y // Greater than or equal to
69
x == y // Equals
x != y // Not equals
x&y // Bitwise and (3 & 6 is 2)
x^y // Bitwise exclusive or (3 ^ 6 is 5)
x|y // Bitwise or (3 | 6 is 7)
x && y // x and then y (evaluates y only if x (not 0))
x || r // x or else y (evaluates y only if x is false(0))
x=y // Assign y to x, returns new value of x
x += y // x = x + y, also -= *= /= <<= >>= &= |= ^=
x?y:z // y if x is true (nonzero), else z
x, y // evaluates x and y, returns y (seldom used)
70