Programming Example
Power series of 3 using c programming language
Power series of 3 using c programming language
#include<stdio.h>
#include<math.h>
void main()
{
int i,m;
for(i=1; i<=20; i++)
{
m = pow(3,i);
printf(" 3^%d = %d \n",i,m);
}
}
3^1 = 3
3^2 = 9
3^3 = 27
3^4 = 81
3^5 = 243
3^6 = 729
3^7 = 2187
3^8 = 6561
3^9 = 19683
3^10 = 59049
3^11 = 177147
3^12 = 531441
3^13 = 1594323
3^14 = 4782969
3^15 = 14348907
3^16 = 43046721
3^17 = 129140163
3^18 = 387420489
3^19 = 1162261467
3^20 = -2147483648
Press any key to continue . . .
Include Libraries:
#include : This includes the standard input-output library for functions like printf.#include : This includes the math library for mathematical functions like pow.Main Function:
void main(): The main function where the execution of the program begins.Variable Declarations:
int i, m: Two integer variables i and m are declared. i will be used as the loop counter, and m will store the result of the power calculation.For Loop:
for(i = 1; i <= 20; i++): A loop that starts with i = 1 and runs until i is 20, incrementing i by 1 on each iteration.Power Calculation:
m = pow(3, i): The pow function from the math library is used to calculate 3i3^i. The result is stored in the variable m.Printing the Result:
printf("3^%d = %d\n", i, m): The printf function is used to print the result in the format "3^i = m", where i is the current loop counter and m is the calculated power of 3.#include #include int main() { int i, m; // Loop from 1 to 20 for(i = 1; i <= 20; i++) { // Calculate 3 raised to the power of i and cast to int m = (int)pow(3, i); // Print the result printf("3^%d = %d\n", i, m); } return 0; // Return success status }
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.