Matlab Python Programming
Matlab Python Programming
Branch:
Course Code:
Academic Year:
INDEX
MATLAB PROGRAMMING
10
11
12
13
14
15
16
17
18
19
20
INDEX
PYTHON PROGRAMMING
10
11
12
13
14
15
16
17
18
19
20
2304501–MATLAB/PYTHON FOR ENGINEERS
Programme B. Tech &
&Branch ECE Sem Category L T P Credits
Course Objectives:
1. Understanding the MATLAB software environment.
2. Demonstrate how MATLAB can be used to solve a range of mathematical problems.
3. Introduction about Polynomials, Curve Fitting, and Interpolation concepts.
4. Introduce basic concepts in Python programming language.
5. Introduce different types of decision control and iterative statements in python.
Now a days programming knowledge has become very essential for engineering
Preamble:
professionals as well as scientists and researchers to develop simulation models,
performing analysis, optimization & decision making. MATLAB and Python are
two excellent tools for visualization and manipulation of engineering data as well
as performing various engineering computations.
Course Contents:
Introduction, conditional branching statements: if, if-else, Nested if, if-elif-else statements, Basic
Loop statements: while, for, Nested Loops, break, continue, pass, else with Loops Statements. A
few example Programs using Python.
Total Hours: 45
Text Books:
Reference Books:
1 Essential MATLAB for Engineers and Scientists – Brian H. Hahan and Daniel T. Valentine,
Elsevier Publications, Fourth Edition.
Web References:
1 https://www.tutorialspoint.com/matlab/matlab_overview.htm
2 https://www.coursera.org/learn/python-for-applied-data-science-ai
COURSE OUTCOMES: BT Mapped
Upon completion of the course, students shall have ability to (Highest Level)
==, ~=, <, >, <=, >= zeros(m,n) Create m x n matrix of zeros
Relational operators
ones(m,n) Create m x n matrix of ones
&&, ||, ~, xor Logical operations
(AND, OR, NOT, XOR) eye(n) Create a n x n identity matrix
; Suppress output display A=diag(x) Create diagonal matrix from vector
... Connect lines (with break) x=diag(A) Get diagonal elements of matrix
% Description Comment meshgrid(x,y) Create 2D and 3D grids
'Hello' Definition of a character vector rand(m,n), randi Create uniformly distributed random
"This is a string" numbers or integers
Definition of a string
randn(m,n) Create normally distributed random
str1 + str2 Append strings
numbers
mathworks.com/help/matlab
Elementary Functions Plotting
sin(x), asin Sine and inverse (argument in radians) plot(x,y,LineSpec) Plot y vs. x
Line styles: (LineSpec is optional)
sind(x), asind Sine and inverse (argument in degrees)
-, --, :, -. LineSpec is a combination of
sinh(x), asinh Hyperbolic sine and inverse (arg. in Markers: linestyle, marker, and
radians) +, o, *, ., x, s, d color as a string.
Analogous for the other trigonometric functions: Colors: Example: "-r"
cos, tan, csc, sec, and cot r, g, b, c, m, y, k, w = red solid line without markers
abs(x) Absolute value of x, complex magnitude title("Title") Add plot title
exp(x) Exponential of x legend("1st", "2nd") Add legend to axes
sqrt(x), nthroot(x,n) Square root, real nth root of real numbers x/y/zlabel("label") Add x/y/z axis label
log(x) Natural logarithm of x x/y/zticks(ticksvec) Get or set x/y/z axis ticks
log2(x), log10 Logarithm with base 2 and 10, respectively x/y/zticklabels(labels) Get or set x/y/z axis tick labels
factorial(n) Factorial of n x/y/ztickangle(angle) Rotate x/y/z axis tick labels
sign(x) Sign of x x/y/zlim Get or set x/y/z axis range
mod(x,d) Remainder after division (modulo) axis(lim), axis style Set axis limits and style
ceil(x), fix, floor Round toward +inf, 0, -inf text(x,y,"txt") Add text
round(x) Round to nearest decimal or integer grid on/off Show axis grid
hold on/off Retain the current plot when
adding new plots
Tables subplot(m,n,p), Create axes in tiled positions
table(var1,...,varN) Create table from data in variables tiledlayout(m,n)
var1, ..., varN yyaxis left/right Create second y-axis
readtable("file") Create table from file figure Create figure window
array2table(A) Convert numeric array to table gcf, gca Get current figure, get current axis
T.var Extract data from variable var clf Clear current figure
T(rows,columns), Create a new table with specified close all Close open figures
T(rows,["col1","coln"]) rows and columns from T
T.varname=data Assign data to (new) column in T Common Plot Types
T.Properties Access properties of T
categorical(A) Create a categorical array
summary(T), groupsummary Print summary of table
join(T1, T2) Join tables with common variables
mathworks.com/help/matlab
Programming Methods Numerical Methods
Functions fzero(fun,x0) Root of nonlinear function
% Save your function in a function file or at the end fminsearch(fun,x0) Find minimum of function
% of a script file. Function files must have the
fminbnd(fun,x1,x2) Find minimum of fun in [x1, x2]
% same name as the 1st function
function cavg = cumavg(x) %multiple args. possible fft(x), ifft(x) Fast Fourier transform and its inverse
cavg=cumsum(vec)./(1:length(vec));
end
Integration and Differentiation
Anonymous Functions
% defined via function handles integral(f,a,b) Numerical integration
fun = @(x) cos(x.^2)./abs(3*x); (analogous functions for 2D and 3D)
trapz(x,y) Trapezoidal numerical integration
mathworks.com/help/matlab
Matrices and Arrays Descriptive Statistics
length(A) Length of largest array dimension sum(A), prod Sum or product (along columns)
size(A) Array dimensions max(A), min, bounds Largest and smallest element
numel(A) Number of elements in array mean(A), median, mode Statistical operations
sort(A) Sort array elements std(A), var Standard deviation and variance
sortrows(A) Sort rows of array or table movsum(A,n), movprod, Moving statistical functions
movmax, movmin, n = length of moving window
flip(A) Flip order of elements in array
movmean, movmedian,
squeeze(A) Remove dimensions of length 1 movstd, movvar
reshape(A,sz) Reshape array cumsum(A), cumprod, Cumulative statistical functions
repmat(A,n) cummax, cummin
Repeat copies of array
smoothdata(A) Smooth noisy data
any(A), all Check if any/all elements are nonzero
nnz(A) histcounts(X) Calculate histogram bin counts
Number of nonzero array elements
find(A) corrcoef(A), cov Correlation coefficients, covariance
Indices and values of nonzero elements
xcorr(x,y), xcov Cross-correlation, cross-covariance
normalize(A) Normalize data
Linear Algebra
detrend(x) Remove polynomial trend
rank(A) Rank of matrix
isoutlier(A) Find outliers in data
trace(A) Sum of diagonal elements of matrix
det(A) Determinant of matrix
poly(A) Characteristic polynomial of matrix
Symbolic Math*
eig(A), eigs sym x, syms x y z Declare symbolic variable
Eigenvalues and vectors of matrix (subset)
inv(A), pinv eqn = y == 2*a + b Define a symbolic equation
Inverse and pseudo inverse of matrix
norm(x) Norm of vector or matrix solve(eqns,vars) Solve symbolic expression
for variable
expm(A), logm) Matrix exponential and logarithm
subs(expr,var,val) Substitute variable in expression
cross(A,B) Cross product
expand(expr) Expand symbolic expression
dot(A,B) Dot product
factor(expr) Factorize symbolic expression
kron(A,B) Kronecker tensor product
simplify(expr) Simplify symbolic expression
null(A) Null space of matrix
assume(var,assumption) Make assumption for variable
orth(A) Orthonormal basis for matrix range
assumptions(z) Show assumptions for
tril(A), triu Lower and upper triangular part of matrix
symbolic object
linsolve(A,B) Solve linear system of the form AX=B fplot(expr), fcontour, Plotting functions for
lsqminnorm(A,B) Least-squares solution to linear equation fsurf, fmesh, fimplicit symbolic expressions
qr(A), lu, chol Matrix decompositions diff(expr,var,n) Differentiate symbolic expression
svd(A) Singular value decomposition dsolve(deqn,cond) Solve differential
gsvd(A,B) Generalized SVD equation symbolically
mathworks.com/help/matlab
© 2024 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
Other product or brand names may be trademarks or registered trademarks of their respective holders.
APPARATUS REQUIRED:
HARDWAR: Personal Computer
SOFTWARE: MATLAB online
PROCEDURE:
1. Login to MathWorks account
2. Click on MATLAB
3. Click on Open MATLAB online
4. Click on New Script
5. Type the program in editor window
6. Save the script file in current directory
7. Run the program
8. If any error occurs in the program, then correct the errors and run it again.
9. Observe the output in command window\ Figure window.
1. The following problems can be solved by writing commands in the Command Window, or
by writing a program in a script file and then executing the file.
22+5.12 √412−5.22 7𝜋 7𝜋
a) b) c)cos ( ) + tan ( ) sin (150 )
50−6.32 𝑒5−100.53 9 15
Script file:
clc;
clear all;
disp('Part (a)')
(22+5.1^2)/(50-6.3^2)
disp('Part (b)')
sqrt(41^2-5.2^2)/(exp(5)-100.53)
disp('Part (c)')
cos(7*pi/9)+tan(7*pi/15)*sind(15)
Command Window:
1
2. Define the variable 𝑥 as 𝑥= 6. 7, then evaluate
Script file:
clc;
clear all;
x=6.7;
disp('Part (a)')
0.01*x^5-1.4*x^3+80*x+16.7
disp('Part (b)')
sqrt(x^3+exp(x)-51/x)
Command Window:
2
3. In the triangle shown a = 5. 3 in., 𝛾 = 42°, and b = 6 in. Define a, 𝛾 , and b as variables, and
then:
(a) Calculate the length c by using the Law of Cosines.
(b) Calculate the angles 𝛼 and β (in degrees) using the Law of Cosines.
(c) Check that the sum of the angles is 180°.
Script file:
clc;
clear all;
a=5.3;
gamma=42;
b=6;
disp('Part (a)')
c=sqrt(a^2+b^2-2*a*b*cosd(gamma))
disp('Part (b)')
alpha = asind(a*sind(gamma)/c)
beta = asind(b*sind(gamma)/c)
disp('Part (c)')
Total = alpha+beta+gamma
Command Window:
3
4. a) Create a row vector that has the following elements: 8, 10/4, 12 x 1.4, 51, tan85°, √26 ,
and 0.15.
0)
b) Create a column vector that has the following elements: 25.5, (14tan58
, 6!, 2.74, 0.0375, and 𝜋.
(2.12+11) 5
Script file:
clc;
clear all;
disp('Part (a)')
disp('Part (b)')
Command Window:
4
5. Create a row vector in which the first element is 1 and the last element is 43, with an
increment of 6 between the elements (1, 7, 13, ... , 43 ).
Script file:
clc;
clear all;
row=1:6:43
Command Window:
6. a) Create the following matrix by typing one command. Do not type individual elements
explicitly.
Script file:
clc;
clear all;
%alternative C = [linspace(7,7,5); linspace(7,7,5)]
C=7*ones(2,5)
Command Window:
b) Create the following matrix by typing one command. Do not type individual elements
explicitly.
Script file:
clc;
clear all;
E=[zeros(2,5); zeros(2) [5:-1:3; 2:-1:0]]
Command Window:
5
Script file:
clc;
clear all;
a=[3 -1 5 11 -4 2];
b=[7 -9 2 13 1 -2];
c=[-2 4 -7 8 0 9];
disp('Part (a)')
matrixA=[a;b;c]
disp('Part (b)')
%alternative matrixB=[b' c' a']
matrixB=[b;c;a]'
Command Window:
6
Script file:
clc;
clear all;
M=reshape(1:18,3,6);
disp('Part (a)')
A=M([1,3],[1,5,6])
disp('Part (b)')
B=M(:,[4,4:6])
disp('Part (c)')
C=M([1,2],:)
disp('Part (d)')
D=M([2,3],[2,3]
Command Window:
7
Script file:
clc;
clear all;
disp('Part (a)')
matrixA=[ones(2) zeros(2)]
disp('Part (b)')
matrixB=[eye(2) zeros(2) ones(2)]
disp('Part (c)')
matrixC=[ones(1,4); zeros(2,4)]
Command window:
8
Script file:
clc;
clear all;
v=[15,8,-6];
u=[3,-2,6];
disp('Part (a)')
v./u
disp('Part (b)')
u'*v
disp('Part (c)')
u*v'
Command window:
9
Script file:
clc;
clear all;
u=[5,-6,9];
v=[11,7,-4];
disp('Part (a)')
dotuv=sum(u.*v)
disp('Part (b)')
dotuv=u*v'
disp('Part (c)')
dotuv=dot(u,v)
Command Window:
10
Script file:
clc;
clear all;
A=[1 -3 5; 2 2 4; -2 0 6];
B=[0 -2 1; 5 1 -6; 2 7 -1];
C=[-3 4 -1; 0 8 2; -3 5 3];
disp('Part (a)')
AplusB=A+B
BplusA=B+A
disp('Part (b)')
AplusBandC=A+(B+C)
AandBplusC=(A+B)+C
disp('Part (c)')
together=3*(A+C)
apart=3*A+3*C
disp('Part (d)')
%element by element
e_by_e_together=A.*(B+C)
e_by_e_apart=A.*B+A.*C
%matrix multiplication
mm_together=A*(B+C)
mm_apart=A*B+A*C
11
Command window:
12
Script file:
clc;
clear all;
A=10*rand(4,4)
disp('Part (a)')
disp('linear algebra multiplication')
R=A*A
disp('Part (b)')
disp('element-by-element multiplication')
R=A.*A
disp('Part (c)')
disp('linear algebra, left division (left multiply by inverse)')
R=A\A
disp('Part (d)')
disp('element-by element, right division')
R=A./A
disp('Part (e)')
disp('determinant')
R=det(A)
disp('Part (f)')
disp('inverse')
R=inv(A)
Command window:
13
14
Script file:
clc;
clear all;
close all;
x=linspace(0,2*pi,200);
f=sin(x).^2.*cos(2*x);
fp=2*sin(x).*cos(x).*cos(2*x)-2*sin(x).^2.*sin(2*x);
plot(x,f,x,fp,'--')
title('f(x)=sin^2(x)cos(2x)')
legend('f(x)','f ''(x)')
xlabel('x-->')
ylabel('y-->')
Figure Window:
15
15. Make a polar plot of the function 𝑟 = 2 sin(3𝜃) sin(𝜃) for 0 ≤ 𝜃 ≤ 2𝜋.
Script file:
clc;
clear all;
close all;
t=-4:.1:4;
theta=linspace(0,2*pi,200);
r=2*sin(3*theta).*sin(theta);
polar(theta,r)
Figure Window:
16
16. Use MATLAB to carry out the following multiplication of two polynomials:
Script File:
clc;
clear all;
pa=[-1 0 5 -1];
pb=[1 2 0 -16 5];
c=conv(pa, pb)
Command window:
17
Script file:
clc;
clear all;
p1=[1 -1.7]; p2=[1 0.5]; p3=[1 -0.7]; p4=[1 1.5]; p5=[1 0];
p12=conv(p1,p2);
p34=conv(p3,p4);
p14=conv(p12,p34);
p=conv(p14,p5)
x=linspace(-1.6,1.8,200);
y=polyval(p,x);
plot(x,y)
xlabel('x')
ylabel('y')
Command window:
18
Script File:
clc;
clear all;
pa=[-10 -20 9 10 8 11 -3];
pb=[2 4 -1];
p=deconv(pa,pb)
Command Window:
19
19a-Script File:
clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x, y, 1);
xplot=linspace(0, 24,100);
yplot=polyval(p1, xplot);
plot(x, y, 'ok', xplot, yplot, 'k', 'linewidth', 2, 'markersize', 8)
xlabel('x', 'fontsize', 18)
ylabel('y', 'fontsize', 18)
Figure window:
20
19b-Script File:
clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x,y,2);
xplot=linspace(0,24,100);
yplot=polyval(p1,xplot);
plot(x,y,'ok',xplot,yplot,'k','linewidth',2,'markersize',8)
xlabel('x','fontsize',18)
ylabel('y','fontsize',18)
Figure window:
21
19c-Script File:
clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x,y,3);
xplot=linspace(0,24,100);
yplot=polyval(p1,xplot);
plot(x,y,'ok',xplot,yplot,'k','linewidth',2,'markersize',8)
xlabel('x','fontsize',18)
ylabel('y','fontsize',18)
Figure window:
22
19d-Script File:
clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x,y,5);
xplot=linspace(0,24,100);
yplot=polyval(p1,xplot);
plot(x,y,'ok',xplot,yplot,'k','linewidth',2,'markersize',8)
xlabel('x','fontsize',18)
ylabel('y','fontsize',18)
Figure window:
23
20. Build a simple Simulink model that takes a sine wave input and amplifies it.
Simulink model:
Output:
24
PYTHON PROGRAMMING
PROCEDURE:
Step 1: Open python editor
Step 2: Write the instructions
Step 3: Save it as a file with file name having the extension .py
Step 4: Run the interpreter
print() : The print() function in Python is used to output data to the console or terminal. It's a
very commonly used function in Python for displaying information, debugging, or
communicating results.
Example:
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 30
Syntax: input(prompt)
25
prompt: A string that will be displayed on the screen before taking the input, letting the user
know what is expected.
Examples:
Output:
Hello, Alice
Since input() returns a string, if you need an integer, you have to convert it using int().
INDENTATION:
In Python, indentation is crucial because it defines the structure and flow of the code. Unlike
many other programming languages, which use braces {} or keywords to define blocks of code,
Python uses indentation to group state An Indentation Error occurs when the spacing is
inconsistent or incorrect, causing Python to fail in understanding the code's structure.
1. Inconsistent use of spaces and tabs: Mixing tabs and spaces in the same code block will
cause an indentation error. Python recommends using 4 spaces for indentation.
Example (incorrect):
def greet():
26
def greet():
print("Hello,")
print("World!")
2. Indentation required for certain blocks: Python expects an indented block after specific
statements like if, for, while, def, class, etc. If you forget to indent after these statements,
you'll get an error.
Example (incorrect):
if True:
if True:
print("This is correct")
3. Unnecessary indentation: Adding extra, unintended indentation where it's not required
will also raise an error.
Example (incorrect):
print("This is correct")
print("This is correct")
4. Misalignment between blocks: If different blocks of code in the same level are not
aligned, Python will throw an error.
27
Example (incorrect):
def func():
print("Start")
Fix: Make sure all statements in the same block have the same indentation:
def func():
print("Start")
print("Correct indentation")
String concatenation:
In Python, string concatenation refers to combining two or more strings into one.
Example:
str1 = "Hello"
str2 = "World"
print(result)
Example:
str1 = "Hello"
str1 += " World"
print(str1)
Output: Hello World
28
Control statements:
if:
if condition:
You can also include elif (else if) and else statements for multiple conditions:
if condition1:
elif condition2:
else:
Example:
x = 10
if x > 20:
elif x == 10:
else:
output:
x is equal to 10
while:
In Python, a while loop repeatedly executes a block of code as long as a specified condition is
True. Here's the syntax:
29
while condition:
# block of code
The loop will continue as long as the condition remains true. If the condition becomes false,
the loop stops
count = 0
count += 1
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Infinite loop
Be careful with conditions that may never become false, as they can cause an infinite loop.
For example:
while True:
count = 0
30
if count == 5:
break
count += 1
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
count = 0
count += 1
if count == 3:
continue
Output:
Count is: 1
Count is: 2
Count is: 4
Count is: 5
31
for:
In Python, a for loop is used to iterate over a sequence (like a list, tuple, string, or range) and
execute a block of code for each element. Here's the basic syntax:
# block of code
Example:
print(fruit)
Output:
apple
banana
cherry
range() in for Loops: The range() function generates a sequence of numbers, which is
commonly used in for loops.
for i in range(5):
print(i)
Output:
32
range() with start and step arguments:
print(i)
Output:
print(char)
Output:
for i in range(3):
for j in range(2):
33
Output:
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
for i in range(5):
if i == 3:
break
print(i)
Output:
for i in range(5):
if i == 2:
continue
print(i)
34
Output:
35
1.Write a program to calculate area of triangle using Heron’s formula.
PYTHON PROGRAM:
print(a,b,c)
S = (a+b+c)/2
area = (S*(S-a)*(S-b)*(S-c))**0.5
OUTPUT:
36
2. Write a program to calculate the distance between two points.
PYTHON PROGRAM:
distance = ((x2-x1)**2+(y2-y1)**2)**0.5
print("Distance=")
print (distance)
OUTPUT:
37
3. Write a program to perform addition, subtraction, multiplication, division, integer division,
and modulo division on two integer numbers.
PYTHON PROGRAM:
add_res = num1+num2
sub_res = num1-num2
mul_res = num1*num2
idiv_res = num1/num2
modiv_res = num1%num2
fdiv_res= float(num1)//num2
OUTPUT:
38
4. Write a program to perform addition, subtraction, division, and multiplication on two
floating point numbers.
PYTHON PROGRAM:
add_res = num1+num2
sub_res = num1+num2
mul_res = num1*num2
div_res = num1/num2
OUTPUT:
39
5. Write a program that demonstrates the use of relational operators.
PYTHON PROGRAM:
x=10
y=20
OUTPUT
40
6. Write a program to calculate area and circumference of a circle.
PYTHON PROGRAM:
area = 3.14*radius*radius
circumference = 2*3.14*radius
OUTPUT:
41
7. Write a program to calculate average of two numbers. Print their deviation.
PYTHON PROGRAM:
avg = (num1+num2)/2
dev1=num1-avg
dev2 =num2-avg
print("AVERAGE", avg)
OUTPUT:
42
8. Write a program to convert degrees Fahrenheit into degrees Celsius.
PYTHON PROGRAM:
OUTPUT:
OUTPUT:
43
9. Write a program to calculate the total amount of money in the piggybank, given the coins
of Rs 10, Rs 5, Rs 2, and Re 1.
PYTHON PROGRAM:
total_amt = num_of_18_coins*10+num_of_5_coins*5+num_of_2_coins*2+num_of_1_coins
OUTPUT:
44
10. Write a program to determine whether a person is not eligible, display how many years
are left to be eligible.
PYTHON PROGRAM:
if(age>=18):
else:
yrs =18-age
print("You have to wait for another " + str(yrs) +" years to cast your vote")
OUTPUT:
45
11. Write a program to find larger of two numbers.
PYTHON PROGRAM:
if(a>b):
large = a
else:
large = b
print("Large = ",large)
OUTPUT:
46
12. Write a program to find whether the given number is even or odd.
PYTHON PROGRAM:
if(num%2==0):
else:
OUTPUT:
47
13. Write a program to determine whether the character entered is a vowel or not.
PYTHON PROGRAM:
else:
OUTPUT:
48
14. Write a program to calculation roots of a quadratic equation.
PYTHON PROGRAM:
D = (b*b)-(4*a*c)
deno = 2*a
if(D>0):
print("REAL ROOTS")
elif(D==0):
root1 = -b/deno
else:
print("IMAGINARY ROOTS")
OUTPUT:
49
15. Write a Program to print 0 to 10 numbers using a while loop.
PYTHON PROGRAM:
i=0
while(i<=10):
i = i+1
OUTPUT:
50
16. Write a program to print the reverse of a given number.
PYTHON PROGRAM:
while num!=0:
temp = num%10
num=num//10
OUTPUT:
51
17. Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero.
PYTHON PROGRAM:
while n>=0:
n = n-1
OUTPUT:
52
8. Write a program using for loop to calculate factorial of a number.
PYTHON PROGRAM:
if(num==0):
fact = 1
else:
fact = 1
fact = fact*i
OUTPUT:
53
19. Write a program to print the following pattern.
**
***
****
*****
PYTHON PROGRAM:
for i in range(1,6):
print()
for j in range(i):
OUTPUT:
54
20. Write a program to print the following pattern.
12
123
1234
12345
PYTHON PROGRAM:
for i in range(1,6):
print()
for j in range(1,i+1):
OUTPUT:
55