Iteración – Ejemplo 7

Enunciado

Dado a y n, calcular e informar la potencia n-ésima de a, an, por productos sucesivos, para n entero positivo, cero o negativo y a <> 0.

Código

Python

def main():
    a, n = int(input("Base/Base: ")),  int(input("Exponente entero/Integer exponent: "))

    p = 1 
    np = abs(n)
    for i in range( 1 , np+1): 
        p = p * a
        
    print( "\n", a ,' ^ ' , n , ' = ', end="" )
    if n >= 0:
        print( p ) 
    else:
        print( 1/p )

    input( "Presionar/Press Enter to exist " ) 
main()

C++

#include <iostream>
using namespace std ;
#include <conio.h>
#include <math.h>

int main()
{
   int a, n, p, np, i ;

   cout << "Base y exponente entero/" ;
   cout << "Base and integer exponent: " ;
   cin >> a >> n ;

   for( p=1, np = abs(n), i=1 ; i<=np ; i++, p*=a ) ;
   
   cout << endl << a << " ^ " << n << " = " ;
   if ( n>=0 )
   	cout << p << endl ;
   else
    	cout << 1.0/p << endl ;
	
   cout << endl << "Presionar/Press enter to exit " ;
   getch() ;
   return 0 ;
}

Pascal

Program Problema8_4 ;
var 
    a, n, p, np, i : longint ;
	
begin
    write ( 'Base y Exponente entero/' ) ;
    write ( 'Base and Integer exponent: ' ) ; 
    readln ( a, n ) ;
    
    p := 1 ; 
    np := abs(n) ;
    for i := 1 to np do 
	p := p * a ;
		
    write( a ,' ^ ' , n , ' = ' ) ;
    if n >= 0 
    then writeln (p) 
    else writeln (1/p:0:15) ;
    
    writeln( 'Presionar/Press Enter to exit' ) ;
    readln ;   
end.

Diagramas