English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

How do you write a function that takes one (non-negative) integer parameter n and uses nested for loops to display the following lines in order:

* A line with all the numbers from n down to 1.
* A line with all the numbers from 2 to n.
* A line with all the numbers from n down to 3.
* .
* .
* .
* A line with just the number n.

when n = 10

similar output is: if n = 3
3 2 1
2 3
3

2007-03-09 04:20:43 · 2 answers · asked by Anonymous in Science & Mathematics Mathematics

2 answers

How about this pseudo code:

for i = 1 to n
{
for j = 1 to n
print n-j+1;
}


i is for each line
j is for each element in the line.

2007-03-09 04:35:11 · answer #1 · answered by modulo_function 7 · 0 0

you have to first write out the output for various examples.
for e.g, let n=7
o/p : 7 6 5 4 3 2 1
2 3 4 5 6 7
7 6 5 4 3
4 5 6 7
7 6 5
6 7
7

so the function would have three for loops;one to count the lines(in the above example there were 7i.e. n lines),one to do the decreasing loop(n to 1,n to 3 etc.) and one to do the increasing loop(2 to n,etc.)

so the body of the function would be something like this :
int i,k;
for(i=1;i<=n;i++) ( this is the counting loop)
{
for(k=n;k>2*i-1;k--) (the decreasing loop)
cout< cout<<'\n'
for(k=2*i;k<=n;k++) (the increasing loop)
cout< }

hope this works.

2007-03-09 12:47:52 · answer #2 · answered by purpleraiment 2 · 0 0

fedest.com, questions and answers