Solution to Practice Exercise
Practice Exercise: Sum of Two Numbers
This exercise demonstrates how data and methods work together in C to calculate the sum of two numbers.
Solution:
C
#include <stdio.h>
// Function to calculate the sum of two numbers
int calculateSum(int num1, int num2) {
// Add the two numbers and store the result
int sum = num1 + num2;
// Return the calculated sum
return sum;
}
int main() {
// Declare variables to store two numbers
int number1, number2;
// Prompt the user to enter two numbers
printf("Enter the first number: ");
scanf("%d", &number1);
printf("Enter the second number: ");
scanf("%d", &number2);
// Call the calculateSum function and store the result
int totalSum = calculateSum(number1, number2);
// Print the sum of the two numbers
printf("The sum of %d and %d is %d\n", number1, number2, totalSum);
return 0;
}
Use code with caution.
Explanation:
Header Inclusion: #include <stdio.h> includes the standard input/output library for functions like printf and scanf.
calculateSum Function:
Return Type: int indicates the function returns an integer value (the sum).
Parameters: int num1 and int num2 are the two numbers to be added.
Implementation:
int sum = num1 + num2; adds num1 and num2 and stores the result in sum.
return sum; returns the calculated sum to the calling function.
main Function:
Variable Declaration: int number1 and int number2 store the user-entered numbers.
User Input: printf prompts the user for input, and scanf reads the entered values into number1 and number2.
Function Call: int totalSum = calculateSum(number1, number2); calls the calculateSum function, passing number1 and number2 as arguments. The calculated sum is stored in totalSum.
Output: printf displays the original numbers and the calculated totalSum.
Return Statement: return 0; indicates successful program execution.
Compiling and Running:
Save the code as a .c file (e.g., sum.c).
Use a C compiler (e.g., GCC) to compile the code: gcc sum.c -o sum (This creates an executable named sum).
Run the program: ./sum
Enter two numbers when prompted. The program will display their sum.
This exercise showcases how data (user-entered numbers) is passed to a method (calculateSum), which performs the calculation (adding numbers) and returns the result (sum). The main function utilizes this result to display the final output.