Difficulty: ★ ☆ ☆ ☆
One of my pastimes is watching math videos. I was a terrible math student, but I enjoy the videos. Occasionally a concept is presented that I can program in C. This month’s Exercise covers one of these concepts.
In this case, the video covered presenting values in different bases. The bases include fractions, negative numbers, square roots, and even e and π. I find such thought experiments to be stimulating and refreshing.
I wrote about base conversion briefly back in 2020, and also about
Alphabedecimal , and I may write about programming in unusual bases in the future. Yet one pattern struck me in the various demonstrations in the video: Occasionally, values in a series alternate between positive and negative.
For example, a series runs: 1, -1, 3, -3, 6, -6, and so on. Programming such a series can be done in a number of ways. Often what’s necessary is a method to generate output alternating between values of 1, -1, 1, -1, 1, -1, and so on. Coding such a loop is your challenge for this month’s Exercise:
Write a loop that outputs 14 values, alternating between positive one and negative one. here’s output from my solution:
1
-1
1
-1
1
-1
1
-1
1
-1
1
-1
1
-1
It seems like a simple task, but as with all programming multiple methods exist to generate the same results. Consider it a brain exercise.
Please try to code a solution on your own before you view my solutions.
Base pi would be quite useful. On a similar note one of the iterative algorithms to calculate pi alternates between + and – for each successive term so there are practical uses for this exercise.
That’s the reason why I wrote it. And it’s relatively simple to code in a number of ways.