This C program calculates the power of each element in an array to a fixed exponent and displays the results.
#include <stdio.h>
#include <math.h>
int main()
{
int numbers[] = {2, 3, 4, 5, 6};
int exponent = 3;
int number_of_elements = sizeof(numbers)/sizeof(numbers[0]);
printf("Number of elements: %d \n", number_of_elements);
for (int x = 0; x < number_of_elements; x++)
{
printf("Number: %d, Exponent: %d, Result: %d \n", numbers[x], exponent, (int)pow(numbers[x], exponent));
}
return 0;
}
Result:
Number of elements: 5
Number: 2, Exponent: 3, Result: 8
Number: 3, Exponent: 3, Result: 27
Number: 4, Exponent: 3, Result: 64
Number: 5, Exponent: 3, Result: 125
Number: 6, Exponent: 3, Result: 216
Process returned 0 (0x0) execution time : 0.078 s
Press any key to continue.
Here's a line-by-line explanation of the code:
#include <stdio.h>
#include <math.h>
These are header files which provide the necessary libraries to perform input/output operations and mathematical calculations using the pow()
function.
int main()
{
int numbers[] = {2, 3, 4, 5, 6};
int exponent = 3;
int number_of_elements = sizeof(numbers)/sizeof(numbers[0]);
This declares an integer array numbers
and initializes it with some values. It also declares an integer variable exponent
and initializes it to 3. The number_of_elements
variable is initialized to the size of the numbers
array divided by the size of one element in the array.
printf("Number of elements: %d \n", number_of_elements);
for (int x = 0; x < number_of_elements; x++)
{
printf("Number: %d, Exponent: %d, Result: %d \n", numbers[x], exponent, (int)pow(numbers[x], exponent));
}
return 0;
}
This displays the number of elements in the numbers
array using printf()
. Then, it loops through each element in the numbers
array using a for
loop, calculates the power of the element raised to the exponent using the pow()
function from the math.h
library, and displays the result using printf()
. Finally, the program ends with a return value of 0.
No comments:
Post a Comment