Hi! Good day to all. I am new here. Anyway, I have been doing my homework a couple of days now and I can't seem to figure out what is wrong with my code. (I am new to C programming by the way.) We are asked to make a program that evaluates the value of a polynomial based on the user's input of N number of terms, value of x, the coefficient of each term and the constant. What bothers me is that when I did some continuous run of the program I found out that the value of the sum every after implementation of the do-while loop does not reset to 0, instead it adds up the value of the last evaluation. Any ideas how to reset it? Here is my code.
Code:
#include <stdio.h>
#include <math.h>
int terms; /*number of terms the polynomial has*/
int x; /* value of x */
int i; /* counter and exponent for evaluation using power function */
int z; /* value of each term every after iteration */
int coefficient;
int sum = 0; /*value of the whole polynomial*/
int main(){
do{
printf("Please enter the number of terms (Enter 0 to exit): ");
scanf("%d", &terms);
if (terms == 0) {
printf("Program terminated. \n");
system("exit");
} else if (terms < 0){
system ("cls");
printf("Please enter valid number of terms! \n");
system ("pause");
} else {
printf("\nPlease enter the value of x: ");
scanf("%d", &x);
for(i = terms-1; i >= 0; i--){
if (i == 0){
printf("\nEnter constant: ");
scanf("%d", &coefficient);
} else {
printf("\nEnter coefficient of x^%d: ", i);
scanf("%d", &coefficient);
}
z = coefficient*pow (x,i);
sum = sum + z;
}
printf("The value of the polynomial is: %d \n", sum);
system ("pause");
}
} while (terms!=0);
}
Thanks a lot to all those who will bother to look at my work and help me. I will mean a lot.