Thursday, February 5, 2009

Write a C program to read in two numbers, x and n, and then compute the sum of this geometric progression: 1+x+x2+x3+����.+xn

#include(stdio.h) // place this '<' & '>' instead of '(' & ')' before stdio.h
#include(conio.h)
#include(math.h)
int main( )
{
int x, n, sum,power;
clrscr( );
printf("Enter the values of x and n:");
scanf("%d%d", &x, &n);
if(n<0 style="font-weight: bold; color: rgb(255, 0, 0);">
{
printf("\nSorry, the formula does not make sense for negative exponents & values");
printf("Enter the values of x and n:");
scanf("%d%d", &x, &n);
sum=1;
for(power=1; power <=n; power++) {
sum=sum+ pow(x,power); }
printf("X value is: %d \nN value is: %d", x, n);
printf("\nSum of the given geometric progression: %d", sum);
}
else
{
sum=1;
for(power=1; power <=n; power++) {
sum=sum+ pow(x,power); }
printf("X value is: %d \nN value is: %d", x, n);
printf("\nSum of the given geometric progression: %d", sum);
}
getch( );
return 0;
}

Output:-
case 1: Suppose x=5, n=3
X value is: 5
N value is: 3
Sum of the given geometric progression: 156
ie., 1+ 5 + 25 + 125 = 156

case 2: Suppose n=-2 or x=-5 then the following message will be displays and it ask for another new values,

Sorry, the formula does not make sense for negative exponents & values.
Enter the values of x and n:5
3
X value is: 5
N value is: 3
Sum of the given geometric progression: 156

No comments:

Post a Comment