TECH 104 Lab 6 Part 1: Go through the following exercise. It will help you understand functions better.
- For the program below, step through the program and record in the memory locations (the boxes to the right) how each variable is changing as the program executes. Discuss this solution with your partner.
- What value is the value of num2 that is printed to the screen at the end of the main program? __________
- Why is the variable result declared inside the function sum, but the num1 and num2 variables are not declared there?_____________________
- Identify the function call, the function declaration, and the function definition.
// function example
| Variables that exist within the main function | |
#include #include
| Value for total is sent back to main function by sum function. | |
int sum(int num1, int num2); void main(void)
| Value for num1 is provided by user | |
{ int total, num1, num2;
| Value for num2 is provided by user | |
printf(\"Enter a whole number: \"); scanf(\"%d\", &num1); printf(\"Enter another whole number: \"); scanf(\"%d\", &num2); total = sum(num1, num2); printf(\"The result is %d \", total); total = sum(8, 5); printf(\"The result is %d \", total); printf(\"Num2 is %d \", num2); system(\"pause\"); }
|
| | Variables that exist within the sum function | |
int sum(int num1, int num2) { int result;
| Value for num1 is sent to the function | |
result = num1 + num2; num2 = 10; return result;
}
| |
| | Value for num2 is sent to the function | |
|
| | Value of result is calculated in the function | |
Note that the num1 and num2 that exist in the main function
are different variables than the num1 and num2 that exist in the sum function. Changing num1 and num2 in the sum function DOES NOT change the num1 and num2 in the main function.
Part 2: Implement the following functions. Make sure that you call the function inside your main.
- Write a function that takes a parameter, score, which represents a score in a test and returns a letter grade based on the following:
score 50 65 = score >= 80 A
- Write a function which, given an integer n, returns the sum 1 + 2 + + n.
Please submitted this completed word document and your c code with the naming format firstNamelastNameStudentLab07.c format