Jump to content

Introduction to Programming/Answers to the exercises

From Wikiversity

Checking An Error Condition

[edit | edit source]

In programming there is rarely one right answer, but for something this simple, your answer should look something like this:

    if (divisor != 0)
    {
        quotient = dividend / divisor;
    }
    else
    {
        ReportErrorMessage;
    }

back

Fibonacci Numbers

[edit | edit source]
int fN = 0;
int fNplus1 = 1;
int counter = 0;

while (counter < 11)
{
    fNplus2 = fN + fNplus1;
    print fN;

    fN = fNplus1;
    fNplus1 = fNplus2;
    counter += 1;
}

A variation, in Perl:

my $counter = 0;
my $F = 1;
my $prev_F = 0;

while( $counter < 10 ) {
    print $F . "\n";
  
    my $x = $F;
    $F = $prev_F + $F;
    $prev_F = $x;

    $counter++;
}

Python 3 version :

f = 1
prevF = 0
counter = 0

while counter < 10:     #While loop. What's underneath it runs until counter becomes (counter < 10).

  	counter += 1 	#You can write this line also as "counter = counter + 1". It assigns 'counter' variable to itself increased by one.
	print(prevF)
	
	prevF += f 		
	
	counter += 1	#We add one to 'counter' variable before each character is printed on screen.
	print(f)
	
	f += prevF
	

back