Homework
March 20, 2020
Today’s exercise is somebody’s homework:
Write a program that displays the digits from 1 to n then back down to 1; for instance, if n = 5, the program should display 123454321. You are permitted to use only a single
for
loop.
The questioner did not specify what should happen when n reaches 10, so we will specify 0 < n < 10.
Your task is to write the requested program; if you like, think of other ways to write that program. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Nifty little exercise. The single loop makes it more challenging. Here is my take on it using Julia: https://pastebin.com/mqqywQn6
Stay healthy!
Klong version
Here are three simple versions in R7RS Scheme.
Pedantic note: I realize that the solution by @programmingpraxis does
not claim conformance to any specific Scheme standard. However, if
portability or conformance to standard Scheme is desired then I
believe that the integers cannot be handed as-is (e.g., without
conversion to strings) to the display procedure. My reading of R7RS
gives implementations a free hand when displaying objects that are not
strings or chars. In my very quick testing, there is at least one
major implementation that will output a space after ‘display’-ing each
integer.
Output:
Here are a few solutions in Python.
Output:
Here’s a solution in C.
Example:
Another solution in C, with n loop iterations instead of 2n:
def updown(n):
return “”.join([f”{n-abs(n-i)}” for i in range(1, 2*n)])
Python solution:
Main sort function
def sort_ints(n):
total_nums = n*2 – 1
int_list = []
Print result
print(sort_ints(5))
======================
OUTPUT
[1, 2, 3, 4, 5, 4, 3, 2, 1]
VBA Solution:
Two Python solutions that use abs or min instead of using an if statement directly.
@Karan N The hwOne function is neat.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int k;
scanf(“%d”,&k);
}