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
For example: if n is 3 and x is 5, then the program computes 1+5+25+125.
Print x, n, the sum
Perform error checking. For example, the formula does not make sense for negative exponents – if n is less than 0.
Have your program print an error message if n<0, then go back and read in the next pair of numbers of without computing the sum. Are any values of x also illegal? If so, test for them too.
Algorithm:
Step 1: Start Step 2: read values of x and n, sum - 1, i = 1 Step 3: check for n & X i) if n <= 0 || x <= 0 ii) print values are not valid iii) read values of x and n Step 4: perform the loop operation i) for(i = 1; i <= n; i++) then follows ii) sum=sum+pow(x, i) Step 5: print sum Step 6: Stop
Program:
#include <stdio.h> #include <conio.h> #include <math.h> void main() { int n, x, i, sum = 0; clrscr(); printf("Enter the limit\n"); scanf("%d", &n); printf("Enter the value of x\n"); scanf("%d", &x); if(x < 0 || n < 0) { printf("illegal value"); } else { for(i = 0; i <= n; i++) sum=sum + pow(x, i); } printf("sum=%d", sum); getch(); }
Input & Output:
Enter the limit 4 Enter the value of x sum=31
-
UpdatedDec 25, 2014
-
Views17,784
Write a C program to find the roots of a quadratic equation
.
Write a C program to count the lines, words and characters in a given text.
Write a C program to find the sum of individual digits of a positive integer.
Write a C program, which takes two integer operands and one operator from the user, performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use switch statement
)
Write a C program to generate all the prime numbers
between 1 and n, where n is a value supplied by the user.
Write C programs that use both recursive
and non-recursive functions
- To find the
factorial
of a given integer. - To find the
GCD
(greatest common divisor) of two given integers.