Thursday 26 January 2012

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>
#include<conio.h>
#include<math.h>
void main( )
{
    int x, n, sum,power;
    clrscr( );
    printf("Enter the values of x and n:");
    scanf("%d%d", &x, &n);
    if(n<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( );
}

No comments:

Post a Comment