0% found this document useful (0 votes)
13 views11 pages

EXP 4 Control Loop

The document outlines various MATLAB programming problems, including calculating the sum of natural numbers, generating Fibonacci series, solving quadratic equations, creating Pascal's Triangle, and using loops with break and continue statements. Each problem includes a clear aim, procedure, and MATLAB code examples. Additionally, it provides practice problems related to multiplication tables and matrix diagonal sums.

Uploaded by

rohans19122003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

EXP 4 Control Loop

The document outlines various MATLAB programming problems, including calculating the sum of natural numbers, generating Fibonacci series, solving quadratic equations, creating Pascal's Triangle, and using loops with break and continue statements. Each problem includes a clear aim, procedure, and MATLAB code examples. Additionally, it provides practice problems related to multiplication tables and matrix diagonal sums.

Uploaded by

rohans19122003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Problem 1: For Loop: Sum of First N Natural Numbers

Aim: To compute the sum of the first natural numbers using a for loop in MATLAB.

Procedure:

Open MATLAB:

Start MATLAB on your computer.


Write the MATLAB Code:

Create a new script file by selecting Home > New Script.


Define a variable N to store the input number.
Initialize a sum variable (sumN = 0).
Use a for loop to iterate from 1 to N, adding each number to sumN.
Execute the Code:

Save the script file with an appropriate name, e.g., sum_natural_numbers.m.


Click Run or press F5 to execute the script.
Observe the Output:

The computed sum is displayed in the Command Window.

CODE

clc;
clear;
disp('--- Sum of First N Natural Numbers using for Loop ---');

N = input('Enter a number: '); % User input


sumN = 0;

for i = 1:N
sumN = sumN + i; % Accumulate sum
end

fprintf('The sum of first %d natural numbers is: %d\n', N,


sumN);

OUTPUT

Enter a number: 15

The sum of first 15 natural numbers is: 120


Problem 2: Fibonacci Series using While Loop in MATLAB

Aim:

To generate the Fibonacci series up to N terms using a while loop in MATLAB..

Apparatus:

MATLAB Software.

Procedure:

Open MATLAB:

Start MATLAB on your computer.

Write the MATLAB Code:

Create a new script file by selecting Home > New Script.

Define a variable N to store the number of terms entered by the user.

Initialize the first two terms of the Fibonacci series (a = 0, b = 1).

Use a while loop to generate the Fibonacci series up to N terms.

Execute the Code:

Save the script file with an appropriate name, e.g., fibonacci_while.m.

Click Run or press F5 to execute the script.

Observe the Output:

The Fibonacci sequence is displayed in the Command Window.


MATLAB Code:
clc;

clear;

disp('--- Fibonacci Series using while Loop ---');

% Input from the user

N = input('Enter the number of terms: ');

% Check if the input is valid

if N <= 0

disp('Please enter a positive integer.');

else

% Initialize the first two terms

a = 0;

b = 1;

count = 0;

% Display the first term

fprintf('Fibonacci Series: %d %d ', a, b);

% While loop to generate Fibonacci series

while count < N-2

c = a + b; % Compute next term

fprintf('%d ', c);

a = b; % Update values

b = c;

count = count + 1;

end

fprintf('\n'); % New line after sequence output

end
Problem 3: Solving a Quadratic Equation using MATLAB

Aim

To find the roots of a quadratic equation using the quadratic formula in MATLAB.

Apparatus:

MATLAB Software.
Procedure
Open MATLAB:

Start MATLAB on your computer.


Write the MATLAB Code:

Create a new script file by selecting Home > New Script.


Prompt the user to enter values of coefficients .
Compute the discriminant .
Use conditional statements (if-else) to check the nature of roots.
Compute and display the roots using the quadratic formula.
Execute the Code:

Save the script file with an appropriate name, e.g., quadratic_formula.m.


Click Run or press F5 to execute the script.
Observe the Output:

The roots of the quadratic equation are displayed in the Command Window

CODE
disp('--- Solving Quadratic Equation using Quadratic Formula ---');

% Input coefficients from the user


a = input('Enter the coefficient a: ');
b = input('Enter the coefficient b: ');
c = input('Enter the coefficient c: ');

% Compute the discriminant


D = b^2 - 4*a*c;

% Check the nature of the roots


if D > 0
% Two distinct real roots
root1 = (-b + sqrt(D)) / (2*a);
root2 = (-b - sqrt(D)) / (2*a);
fprintf('The roots are real and distinct: %.2f and %.2f\n', root1, root2);
elseif D == 0
% One real repeated root
root = -b / (2*a);
fprintf('The roots are real and repeated: %.2f\n', root);

else
% Complex roots
real_part = -b / (2*a);
imag_part = sqrt(abs(D)) / (2*a);
fprintf('The roots are complex: %.2f + %.2fi and %.2f - %.2fi\n', ...
real_part, imag_part, real_part, imag_part);
end

OUTPUT

Solving Quadratic Equation using Quadratic Formula

Enter the coefficient a: 1

Enter the coefficient b: 5

Enter the coefficient c: 4

The roots are real and distinct: -1.00 and -4.00

Problem 4: Pascal’s Triangle using Nested Loops in MATLAB

Aim

To generate and display Pascal’s Triangle using nested loops in MATLAB.

Apparatus:

MATLAB Software.

Procedure:

Open MATLAB:

Start MATLAB on your computer.

Write the MATLAB Code:

Create a new script file by selecting Home > New Script.

Prompt the user to enter the number of rows for Pascal’s Triangle.
Use nested loops to compute and display Pascal’s Triangle.

The outer loop iterates over the rows.

The inner loop computes and prints binomial coefficients using nchoosek().

Execute the Code:

Save the script file as pascals_triangle.m.

Click Run or press F5 to execute the script.

Observe the Output:

The Pascal’s Triangle will be printed in the Command Window.

CODE

disp('--- Pascal’s Triangle using Nested Loops ---');

% Input number of rows from the user


n = input('Enter the number of rows for Pascal''s Triangle: ');

% Generate Pascal's Triangle


for i = 0:n-1
for j = 0:i
fprintf('%d ', nchoosek(i, j)); % Compute binomial coefficient
end
fprintf('\n'); % Move to the next line after each row
end

OUTPUT

Enter the number of rows for Pascal's Triangle: 6

11

121

1331

14641

1 5 10 10 5 1
Problem 5: Loop with Break & Continue - Skipping Even Numbers in
MATLAB

Aim

To understand the usage of break and continue statements in a for loop by printing
only odd numbers up to a given limit while skipping even numbers.

Apparatus:

MATLAB Software.

Procedure:

Open MATLAB:

Start MATLAB on your computer.

Write the MATLAB Code:

Create a new script file by selecting Home > New Script.

Define a for loop to iterate through numbers from 1 to N.

Use continue to skip even numbers.

Use break to stop execution when the number is greater than 7.

Execute the Code:

Save the script file as loop_break_continue.m.

Click Run or press F5 to execute the script.

Observe the Output:

The numbers printed should be odd numbers up to 7.

The loop should stop if a number exceeds 7.

CODE
disp('--- Loop with Break & Continue: Skipping Even Numbers ---');

% Input the limit N


N = input('Enter the limit: ');

% Loop from 1 to N
for i = 1:N
% Skip even numbers
if mod(i,2) == 0
continue; % Skip this iteration and move to next
end

% Display the odd number


fprintf('%d ', i);

% Stop the loop if number is greater than 7


if i > 7
break;
end
end
fprintf('\n'); % Move to next line after loop ends

Odd numbers: 1, 3, 5, 7, 9 are printed.

Even numbers: 2, 4, 6, 8, 10 are skipped using continue.

Break condition: When i = 9, the loop stops using break.

PRACTISE PROBLEMS

1. Nested for Loop: Multiplication Table


disp('--- Multiplication Table using Nested for Loop ---');

rows = input('Enter the number of rows: '); % User input


cols = input('Enter the number of columns: ');

% Generate multiplication table


for i = 1:rows
for j = 1:cols
fprintf('%4d', i * j); % Format output neatly
end
fprintf('\n');
end

Expected Output (for rows = 3, cols = 3):


1 2 3
2 4 6
3 6 9

2. Matrix Diagonal Sum


clc;

clear;

disp('--- Sum of Diagonal Elements of a Matrix --


-');

% Input matrix dimensions

n = input('Enter the number of rows: ');

m = input('Enter the number of columns: ');

% Check if matrix is square

if n ~= m

disp('Error: The matrix must be square.');

else

% Initialize matrix A

A = zeros(n, n);

% Input matrix elements from the user

disp('Enter the matrix elements row-wise:');

for i = 1:n

for j = 1:n

A(i, j) = input(sprintf('Enter
element A(%d,%d): ', i, j));

end

end
% Display the entered matrix

disp('Matrix A:');

disp(A);

% Compute the sum of diagonal elements

diagonal_sum = 0;

for i = 1:n

diagonal_sum = diagonal_sum + A(i, i);

end

% Display the result

fprintf('Sum of diagonal elements: %d\n',


diagonal_sum);

% Compare with built-in MATLAB function

fprintf('Using trace() function: %d\n',


trace(A));

end

Factorial of a Number using While Loop


clc;
clear;
disp('--- Factorial using while Loop ---');

% Input from the user


num = input('Enter a positive integer: ');

% Check if the input is valid


if num < 0
disp('Factorial is not defined for negative numbers.');
elseif num == 0
disp('Factorial of 0 is: 1');
else
% Initialize factorial variable
fact = 1;
i = num;

% While loop to calculate factorial


while i > 0
fact = fact * i;
i = i - 1;
end

% Display the result


fprintf('Factorial of %d is: %d\n', num, fact);
end

You might also like