Vous êtes sur la page 1sur 4

002-Topic: Simple Loops and Nested Loops Exercises

Course Learning Outcomes (CO):


CO-2: Use algorithm development tools to develop a computer solution for engineering
related problems, which include the skills necessary to:
(c) Apply the repetition structure to the solution of problems.

1.- A for loop running through a 2-D array of values. Explain the output of the following
loop. Is the ii loop’s control variable running row- or column-wise?

2.- Loops, accumulators and series. Write a program to compute the sum of
the multiples of seven in the range [7,777].

% documentation

clc, clear
x=[7:7:777];

s=0;

for ii=1:1:length(x)

s = s+x(ii);
end

fprintf(‘The sum of the multiples of 7 in the range [7,777] is %e \n’, s);


OUTPUT

The sum of the multiples of 7 in the range [7,777] is 43512

3.- Nested Loops. How many times will this program print "Hola Mundo"?

for a=10:10:50
for b=0:0.1:1
disp('Hola Mundo')
end
end

4.- A Tricky Loop. What sequence of numbers will the following for loop print?

n = 10;
for j = 1:n
n = n-1;
j
end

Explain why this code does what it does.

5.- Loop Indices. How many times will this program print "Bonjour Monde"?

for a=-1:1:-50
disp('Bonjour Monde')
end

6.- Loop Indices. How many times will this program print "Guten Tag Welt"?

for a=-1:-1:-50
disp('Guten Tag Welt')
end

7.- Loop Indices. How many times will this program print "Hello There World"?

for a=0:1:50
disp('Hello There World')
end
8.- Nested Loops Indices. What is the values of the loops parameters (i.e., a, b, c, d, e,
f, and g) to print

1 for j=a:b:c
12 for i=d:e:f
123 fprintf(‘%d’,g);
1234 end
12345 fprintf(‘\n’);
end

1.- a=5, b=-1, c=1, d=1, e=1, f=j, g=i


2.- a=1, b=1, c=5, d=j, e=1, f=5, g=j
3.- a=1, b=1, c=5, d=1, e=1, f=j, g=i
4.- a=5, b=-1, c=1, d=j, e=-1, f=1, g=j
5.- a=1, b=1, c=5, d=j, e=-1, f=1, g=i

ANSWER
3

for j=1:1:5
for
i=1:1:j
fprintf(‘%d’,i)
; end
end

9.- Nested Loop Indices. What is the values of the loops parameters (i.e, a, b, c, d, e, f,
and g) to print

54321 for j=a:b:c


4321 for i=d:e:f
321 fprintf(‘%d’,g);
21 end
1 fprintf(‘\n’);
end

1.- a=5, b =-1, c=1, d=5, e=-1, f=j, g=i


2.- a=1, b=1, c=5, d=1, e=1, f=j, g=i
3.- a=1, b=1, c=5, d=1, e=1, f=j, g=j
4.- a=5, b =-1, c=1, d=j, e=-1, f=1, g=j
5.- a=5, b =-1, c=1, d=j, e=-1, f=1, g=i

ANSWER is 5

for j=5:-1:1
for i=j:-1:1
fprintf(‘%d’,i);
end
fprintf(‘\n’);
end

10.- Nested Loops Indices. What is the values of the loops parameters (i.e, a, b, c, d, e,
f, and g) to print

55555 for j=a:b:c


4444 for i=d:e:f
333 fprintf(‘%d’,g);
22 end
1 fprintf(‘\n’);
end

1.- a=5, b =-1, c=1, d=j, e=-1, f=1, g=i


2.- a=5, b=-1, c=1, d=1, e=1, f=j, g=j
3.- a=5, b =-1, c=1, d=j, e=-1, f=1, g=j
4.- a=5, b =-1, c=1, d=5, e=-1, f=j, g=i
5.- a=1, b=1, c=5, d=1, e=1, f=j, g=i

ANSWER
2

for j=5:-1:1
for i=1:1:j
fprintf(‘%d’,j);
end
fprintf(‘\n’);
end

Vous aimerez peut-être aussi