C++ Exercises: Find power of any number using for loop
C++ For Loop: Exercise-62 with Solution
Write a program in C++ to find the power of any number using a for loop.
Visual Presentation:
Sample Solution:-
C++ Code :
#include <iostream> // Including the input/output stream library
using namespace std; // Using the standard namespace
int main() // Main function where the execution of the program starts
{
int bs, ex, num = 1, i; // Declare integer variables bs, ex, num, and i
// Display messages asking for input
cout << "\n\n Find power of any number using for loop:\n";
cout << "---------------------------------------------\n";
cout << " Input the base: ";
cin >> bs; // Read the base value from the user
cout << " Input the exponent: ";
cin >> ex; // Read the exponent value from the user
// Loop to calculate the power of the base number
for (i = 1; i <= ex; i++)
{
num = num * bs; // Multiply num by base 'ex' times to get the power
}
// Display the result of base raised to the exponent
cout << bs << " ^ " << ex << " = " << num << endl;
}
Sample Output:
Find power of any number using for loop: --------------------------------------------- Input the base: 2 Input the exponent: 5 2 ^ 5 = 32
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C++ to print all ASCII character with their values.
Next: Write a program in C++ to enter any number and print all factors of the number.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-62.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics