Chapter 5 (not understanding flow)


#1

Here is my answer to the challenge at the end of Chapter 5. I worked it for about an hour and finally came up with a solution that spits out the correct answer, however, I have little idea about how this program is delivering the answer. So…I think the best way to go about my question is to tell you what I think is going on and then hopefully someone can set me straight.

  1. There are two frames in this program.
  2. When I compile and run this program it starts with the “main” function first and then proceeds to wherever “main” has told it to go. (this is a little confusing because the graphics in the book always show main on the bottom of the stacks. If its first why is it on the bottom?)
  3. I have declared my variables and known values to be floating, this means that they can contain 8 digits on either side of the decimal.
  4. After the floatAngleC = is read the program jumps up to my second frame and labeled “float remainingAngle(float angleA, float angleB)”
  5. The function of the second frame is "float angleC = 180 - angleA - angleB;
    return angleC;
  6. angleC is returned to the printf command at the end of “main”
  7. program ends

#include <stdio.h>

float remainingAngle(float angleA, float angleB)
{
float angleC = 180 - angleA - angleB;
return angleC;
}

int main(int argc, const char * argv[])
{
float angleA = 20.0;
float angleB = 60.0;
float angleC = remainingAngle(angleA,angleB);
printf(“The third angle is %.2f\n”, angleC);
return 0;
}


#2

Better to say: there are two functions. A frame is a piece of data that’s saved (on a stack) when a function is invoked so that the function can get back to the point in the environment in which it was invoked.

The reason for that is that main is the very first function that runs in your code; so its frame will be pushed onto the stack first and thus will be on the top of the stack (will also be on the bottom of the stack assuming that the stack was empty before main was pushed.)

However, if main calls a function, that function’s frame will also be pushed onto the stack; now its frame will be on the top of the stack, main’s frame underneath it. And so on.

Remember: the stack is a LIFO container of objects, a Last-In-First-Out container. So the last object pushed will always be on the top of the stack; it will also be popped off first.

Push 3 objects on to an empty stack.

.      Empty stack

push A :
A <--- Top, Bottom

push B :
B <--- Top
A <--- Bottom

push C :
C <--- Top
B
A <--- Bottom

Now pop them off.
pop :  ---> C

B <--- Top
A <--- Bottom

pop :  ---> B

A <--- Top, Bottom

pop :  ---> A

.    Empty stack

Better to say: main invokes remainingAngle, which calculates and returns the value of the third angle of a triangle; the value is assigned to angleC.

Better to say: The function of remainingAngle is to calculate the value of the third angle given the values of the other two angles of a triangle.


#3

Thank you ibex10.