Login

Welcome, Guest. Please login or register.

April 27, 2024, 06:50:07 pm

Author Topic: MJRomeo81's General Programming Quizzes and Tips  (Read 2805 times)  Share 

0 Members and 1 Guest are viewing this topic.

MJRomeo81

  • Part of the furniture
  • *****
  • Posts: 1231
  • Princeps
  • Respect: +167
MJRomeo81's General Programming Quizzes and Tips
« on: July 08, 2012, 02:44:24 am »
+3
An understanding of algorithms and especially data types is an area of the study design that many students "assume" to know yet they stuff up in the exam. So in this thread I will be posting some simple language-independent questions for those that wish to brush up their skills. When a few people respond to the thread I will post the answers and explain each programming concept.

1) What is the output of the following code fragment?

double number = (1/3) * 3;
Print number;

2) Given the following code fragment that converts from degrees Celsius to degrees Fahrenheit, answer the following questions:

double celsius = 20;
double fahrenheit;
fahrenheit = (9/5) * celsius + 32.0;

a) What is the value assigned to fahrenheit?
b) Explain what is actually happening, and what the programmer likely wanted.
c) Rewrite the code as the programmer intended.

3)

a) How do you write a single line comment?
b) What about a multi-line (block) comment?

4)

Trace the following code fragment, that is, step through the boolean logic to evaluate whether the Boolean statement is true or false.

count = 8

NOT ( (count < 3)  OR  (count > 7) )


Bonus question:

Consider the following code fragment. Assume that all variables are integers.

if ( (kids != 0) && ( (pieces / kids) >=2) )
  Print("Each child may have two pieces of yummy delicious chicken.")


Explain specifically how short circuit evaluation prevents a run time error in the case that a specific numeric value is assigned to the 'kids' variable.
Currently working in the IT Industry as an Oracle DBA (State Government)

Murphy was an optimist

Bachelor of Information Technology @ La Trobe (Melbourne) - Completed 2014
WAM: 91.96
The key, the whole key, and nothing but the key, so help me Codd.

Subjects I tutored during my time at LTU:
CSE2DBF (Database Fundamentals)
CSE1IS (Information Systems)
CSE2DES (System Design Engineering)

Quote
“If I had an hour to solve a problem I'd spend 55 minutes defining the problem and 5 minutes thinking about solutions.”
― Albert Einstein

Lasercookie

  • Honorary Moderator
  • ATAR Notes Legend
  • *******
  • Posts: 3168
  • Respect: +326
Re: MJRomeo81's General Programming Quizzes and Tips
« Reply #1 on: July 08, 2012, 02:39:07 pm »
+2
Awesome questions, I'll have a shot at them, let's see how I fare. I'm not too sure on question 1 and 2, particularly with the behavior with double. I think the problem might be integer division, but I'm not sure if we deal with that in ITSD or if there's something else I'm overlooking. I've listed my ideas for those questions anyway.

1) What is the output of the following code fragment?
double number = (1/3) * 3;
Print number;
The answer should be one.

I'm curious as to why double was used, as opposed to float, since it'd be unnecessary usage of memory considering that we're only dealing with numbers like 25.20. 

What I know about double:
Double is a data type, where double is shorthand for double precision, as opposed to single precision (precision is the number of digits in the number)? If I'm not mistaken, single precision is equivalent to floating point numbers.

I can't remember the exact numbers that it covers: I know they're huge numbers and that it can deal with numbers something like (1, followed by 300 zeroes) and (not sure if that's correct)

I also know that division is a bit weird at times, depending on what data types you're using. Division involving integers returns integers, division involving at least one floating point returns a floating point.

We have 1/3, division involving two integers, so that would evaluate as zero, and hence the final output would be zero.

If that is the problem to fix that we could go (basically making 1 and 3 not integers) :
Code: [Select]
float number = (1.0/3.0) * 3;
print number;

which would output: 1

2) Given the following code fragment that converts from degrees Celsius to degrees Fahrenheit, answer the following questions:

double celsius = 20;
double fahrenheit;
fahrenheit = (9/5) * celsius + 32.0;

a) What is the value assigned to fahrenheit?
b) Explain what is actually happening, and what the programmer likely wanted.
c) Rewrite the code as the programmer intended.
Again, the only problem I can think of is integer division.

a)

b) I don't think there would be an error with BODMAS here.

The programmer would have wanted
The decimal point would just depend on how you format the output.

There could also be an integer division error, with the 9/5 (two integers), getting 1 instead of 1.8 like we'd want, so the program would output 52 instead.

The other problem would be is that it's unnecessary to use double for the numbers we're dealing with here?

c)

Code: [Select]
float celsius = 20;
float fahrenheit;
fahrenheit = (9.0/5.0) * celsius + 32.0;

3)
a) How do you write a single line comment?
b) What about a multi-line (block) comment?
Depends on the language I guess, but single line comments are usually along the lines of this:
# Comment
or
// Comment

and block comments are usually
/* rooooooooooooooooo
oooooooooooooooooooo
ooooooooooooooooooar */

or you can just repeat single-line comments
#A
#A
#A

4)
Trace the following code fragment, that is, step through the boolean logic to evaluate whether the Boolean statement is true or false.

count = 8

NOT ( (count < 3)  OR  (count > 7) )
NOT ( (count < 3)  OR  (count > 7) )

This is basically saying that count will not be true if it's less than 3 or if it's greater than 7.
This means that if count is between 3 and 7, it's true.
If it's equal to 3 or 7, it'll also evaluate true.

Since count is 8, it's false.

Bonus question:

Consider the following code fragment. Assume that all variables are integers.

if ( (kids != 0) && ( (pieces / kids) >=2) )
  Print("Each child may have two pieces of yummy delicious chicken.")


Explain specifically how short circuit evaluation prevents a run time error in the case that a specific numeric value is assigned to the 'kids' variable.
The condition for the if statement is:
If kids is not equal to zero AND if pieces/kids is greater than equal to 2.

Looking at the code, it seems to be saying that if we do have kids around, and we have enough pieces of chicken to pass around so that each kid will at least get 2 pieces, then we give out the chicken.

Since we're dealing with integers, we can have numbers such as -5, -3, 0, 1, 2, 3. That's assuming that it's signed integers. If it's unsigned integers, then the following sentence wouldn't matter since we only have positive numbers and zero (e.g. 0, 1, 2, 3).

If kids was a negative value, the if statement wouldn't run, since pieces/kids would be a negative number and hence less than 2. If pieces and kids were a negative value, it's possible you could get something like -6/-2 = 3 and the code would run.

I'm not entirely sure what short-circuit evaluation is, but I'll go out on a limb and guess that it's referring to the kids != 0 bit.
If kids equaled zero, then we would get a division by zero error with the pieces/kids condition. Since the condition requires BOTH to be true, if kids = 0, then the division by zero error shouldn't matter.




I do have a question though, does the order you list them in matter?
e.g. will if ( (kids != 0) && ( (pieces / kids) >=2) ) and if ( ( (pieces / kids) >=2) && (kids != 0)) produce different results?

How is boolean logic actually evaluated by the computer?

My guess at the answer is that it won't produce different results. If pieces/kids did evaluate to zero, I assume that it would move onto evaluating the other condition straight away, rather than giving a run-time error immediately there. (I'll probably google some stuff now)

MJRomeo81

  • Part of the furniture
  • *****
  • Posts: 1231
  • Princeps
  • Respect: +167
Re: MJRomeo81's General Programming Quizzes and Tips
« Reply #2 on: July 08, 2012, 04:39:34 pm »
+1
Well done laseredd!

Your answers are correct. Instead of repeating solutions (or providing alternatives) I will explain the programming concepts under appropriate headings, with some selected examples.


Integer and Floating-Point Division

When used with one or both operands of type double or float, the division operator / behaves as you might expect. However, when used with two operands of type int, the division operator yields the integer part resulting from division. In other words, integer division discards the part after the decimal point. So, 10/3 is 3 (not 3.3333…), 5/2 is 2 (not 2.5), and 11/3 is 3 (not 3.6666…). Notice that the number is not rounded; the part after the decimal point is discarded no matter how large it is.

This can be a problem if you expect a fraction. Moreover, the problem can easily go unnoticed, resulting in a program that looks fine but is producing incorrect output without your even being aware of the problem. For example, suppose you are a landscape architect who charges $5,000 per mile to landscape a highway, and suppose you know the length in feet of the highway you are working on. The price you charge can easily be calculated by the following statement:

totalPrice = 5000 * (feet/5280.0);

This works because there are 5,280 feet in a mile. If the stretch of highway you are landscaping is 15,000 feet long, this formula will tell you that the total price is

5000 * (15000/5280.0)

Your program obtains the final value as follows:  15000/5280.0 is computed as 2.84. Then the program multiplies 5000 by 2.84 to produce the value 14200.00. With the aid of your program, you know that you should charge $14,200 for the project. Now suppose the variable feet is of type int, and you forget to put in the decimal point and the zero, so that the assignment statement in your program reads:

totalPrice = 5000 * (feet/5280);

It still looks fine, but will cause serious problems. If you use this second form of the assignment statement, you are dividing two values of type int, so the result of the division feet/5280 is 15000/5280, which is the int value 2 (instead of the value 2.84, which you think you are getting). So the value assigned to totalPrice is 5000*2, or 10000.00. If you forget the decimal point, you will charge $10,000. However, as we have already seen, the correct value is $14,200. A missing decimal point has cost you $4,200. Note that this will be true whether the type of totalPrice is int or double; the damage is done before the value is assigned to totalPrice.

A type cast can always be performed on one of the variables to avoid integer division (if both variables in the equation are ints) but this is probably outside the scope of the course.


Commenting code
One line comment      // comment the line
Block comment       /* Comment */


It is difficult to say just how many comments a program should contain. The only correct answer is “just enough,” which of course conveys little to the novice programmer. It will take some experience to get a feel for when it is best to include a comment.Whenever something is important and not obvious, it merits a comment. However,providing too many comments is as bad as providing too few. A program that has a comment on each line is so buried in comments that the structure of the program is hidden in a sea of obvious observations. Comments like the following contribute nothing to understanding and should not appear in a program:

interest = balance * rate; //Computes the interest.

A well-written program is what is called self-documenting, which means that the structure of the program is clear from the choice of identifier names and the indenting pattern. A completely self-documenting program would need none of these // comments that are only for the programmer who reads or modifies the code.


Boolean Logic and Short Circuit Evaluation

Most programming languages take an occasional shortcut when evaluating a Boolean expression. Notice that in many cases, you need to evaluate only the first of two or more subexpressions in a Boolean expression. For example, consider the following:

(savings >= 0) && (dependents > 1)

If savings is negative, then (savings >= 0) is false, and when one subexpression in an && (AND) expression is false, then the whole expression is false, no matter whether the other expression is true or false. Thus, if we know that the first expression is false, there is no need to evaluate the second expression. A similar thing happens with || (OR) expressions. If the first of two expressions joined with the || operator is true, then you know the entire expression is true, whether the second expression is true or false.

Programming compilers use these facts to save itself the trouble of evaluating the second subexpression in a logical expression connected with an
&& or an ||.  This method of evaluation is called short-circuit evaluation or lazy evaluation. Here is an example of that illustrates the advantage of short-circuit evaluation (same question in my original post):

if ( (kids != 0) && ((pieces/kids) >= 2) )
Print("Each child may have two pieces!");

If the value of kids is not zero, this statement involves no subtleties. However, suppose the value of kids is zero and consider how short-circuit evaluation handles this case. The expression (kids != 0) evaluates to false, so there would be no need to evaluate the second expression. Using short-circuit evaluation, the entire expression is false, without bothering to evaluate the second expression. This prevents a run-time error, since evaluating the second expression would involve dividing by zero.


I do have a question though, does the order you list them in matter?
e.g. will if ( (kids != 0) && ( (pieces / kids) >=2) ) and if ( ( (pieces / kids) >=2) && (kids != 0)) produce different results?

How is boolean logic actually evaluated by the computer?

My guess at the answer is that it won't produce different results. If pieces/kids did evaluate to zero, I assume that it would move onto evaluating the other condition straight away, rather than giving a run-time error immediately there. (I'll probably google some stuff now)

If the computer attempted to divide by zero, a run time error will occur. So yes, the order does matter and it's why short circuit evaluation can be a handy tool.
Currently working in the IT Industry as an Oracle DBA (State Government)

Murphy was an optimist

Bachelor of Information Technology @ La Trobe (Melbourne) - Completed 2014
WAM: 91.96
The key, the whole key, and nothing but the key, so help me Codd.

Subjects I tutored during my time at LTU:
CSE2DBF (Database Fundamentals)
CSE1IS (Information Systems)
CSE2DES (System Design Engineering)

Quote
“If I had an hour to solve a problem I'd spend 55 minutes defining the problem and 5 minutes thinking about solutions.”
― Albert Einstein

paulsterio

  • ATAR Notes Legend
  • *******
  • Posts: 4803
  • I <3 2SHAN
  • Respect: +430
Re: MJRomeo81's General Programming Quizzes and Tips
« Reply #3 on: July 08, 2012, 04:49:41 pm »
0
I also know that division is a bit weird at times, depending on what data types you're using. Division involving integers returns integers, division involving at least one floating point returns a floating point.

We have 1/3, division involving two integers, so that would evaluate as zero, and hence the final output would be zero.

If that is the problem to fix that we could go (basically making 1 and 3 not integers) :
Code: [Select]
float number = (1.0/3.0) * 3;
print number;

which would output: 1
Again, the only problem I can think of is integer division.

I actually want to test this out to see what happens, so what I'll try to do is define an integers setting them as 1 and 3 and then dividing them to see what I get.

OK, so trial 1:


Trial 2:


Trial 3:



MJRomeo81

  • Part of the furniture
  • *****
  • Posts: 1231
  • Princeps
  • Respect: +167
Re: MJRomeo81's General Programming Quizzes and Tips
« Reply #4 on: July 08, 2012, 05:51:24 pm »
+1
Test 1 in C:

http://i45.tinypic.com/t8u2b4.png


Test 2 in C:

http://i47.tinypic.com/ncnnr7.png

Test 3 in Java:

http://i49.tinypic.com/vhxlds.png

Solution? Forget about Visual Basic.
« Last Edit: July 08, 2012, 05:53:00 pm by MJRomeo81 »
Currently working in the IT Industry as an Oracle DBA (State Government)

Murphy was an optimist

Bachelor of Information Technology @ La Trobe (Melbourne) - Completed 2014
WAM: 91.96
The key, the whole key, and nothing but the key, so help me Codd.

Subjects I tutored during my time at LTU:
CSE2DBF (Database Fundamentals)
CSE1IS (Information Systems)
CSE2DES (System Design Engineering)

Quote
“If I had an hour to solve a problem I'd spend 55 minutes defining the problem and 5 minutes thinking about solutions.”
― Albert Einstein