Problem with recursive function, 2 parameters

Asked

Viewed 259 times

-1

I’m trying to write this code using recursiveness:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

  int potencia(int i, int j)
  {
    return (j > 0) ? 1 : (potencia(i , j)i * j - 1) * i;
  }

  int main(void)
  {
    setlocale(LC_ALL, "");

    int valor1;
    int valor2;

    printf("Insira um valor: ");    scanf("%i", &valor1);
    printf("Insira outro valor: "); scanf("%i", &valor2);

    printf("Resultado da potencia: ", potencia(valor1, valor2));

    return 0;
  }

But an error is shown to me

F:\Atividade 47.c|7|error: expected ')' before 'i'|

I’ve changed everything possible and so far nothing has worked, someone can help me solve this problem?

3 answers

1

(potencia(i , j) <qual operador vai aqui?> i * j - 1)

You can’t have two operands without one operator. Missing put what needs to be done with the power of e and j related to i. Putting an operator there will work.

1

I’m gonna go through some things that are going on with your code:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

  int potencia(int i, int j)
  {
    return (j > 0) ? 1 : (potencia(i , j)i * j - 1) * i;
    // ----------------------------------^
    //                                    \__ O Maniero falou desse operador aqui
  }

  int main(void)
  {
    setlocale(LC_ALL, "");

    int valor1;
    int valor2;

    printf("Insira um valor: ");    scanf("%i", &valor1);
    printf("Insira outro valor: "); scanf("%i", &valor2);

    printf("Resultado da potencia: ", potencia(valor1, valor2));
    // ---------------------------^
    //                             \__ faltou o indicador de formatação de inteiro; o que vem aqui?

    return 0;
  }

Taking advantage, your recursive formula is exactly like this:

                 / j > 0: 1
potência(i, j) ={
                 \ j <= 0: potência(i, j) i * j-1

If we try to find the value of potência(5, 1), what would be the expected result? If we follow the logic of its formula, how j > 0, the result would be 1. That’s right?

If we take the formula and try to calculate for potência(5, 0)? I’ll take the first step of iteration:

potência(5, 0) ==> potência(5, 0) 5 * 0-1

Is this recursion right? It will eventually converge to some value?

-2

The full Solution in C#

using System;
class Power{
  static void Main(string[] args){
    long number1, number2, result;
    Console.Write("Type the BASE number: ");
    number1 = Convert.ToInt32(Console.ReadLine());
    Console.Write("Define its EXPONENT: ");
    number2 = Convert.ToInt32(Console.ReadLine());
    result = power(number1, number2);
    Console.WriteLine("SOLUTION: {0} ^ {1} = {2}", number1, number2, result);
  }
  static long power(long n1, long n2){
    if(n2 == 0){
      return 1;
    }
    return n1 * power(n1, n2 - 1);
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.