In: Computer Science
1/Write a C program that asks the user to enter 5 nums and adds each number to a total. The program should then display the total. To add to the total, the program must call the function void sum(int value, int *ptotal) passing the value the user entered and the address of the total (a local variable in main). The function should add the value to the total. Note that the function is void and does not return anything. Don't forget to initialize the total to 0 in main. 2/Modify the previous program to get the value by calling the function void GetValue(int *pvalue) for each of the 5 values entered by the user. The program should still call the sum function to calculate the sum and should still display the total.
Below is the complete C code. If you face any difficulty while understanding the code, Pleae let me know in the comments.
1.
Code:
#include <stdio.h>
void sum(int value, int *ptotal) {
*ptotal += value;
}
int main() {
int total = 0;
int pvalue;
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5 ; i++) {
scanf("%d", &pvalue);
sum(pvalue, &total);
}
printf("Total: %d", total);
return 0;
}
2. Program after adding GetValue:
Code:
#include <stdio.h>
void GetValue(int *pvalue) {
scanf("%d", &(*pvalue));
}
void sum(int value, int *ptotal) {
*ptotal += value;
}
int main() {
int total = 0;
int pvalue;
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5 ; i++) {
GetValue(&pvalue);
sum(pvalue, &total);
}
printf("Total: %d", total);
return 0;
}
Output: