Create a recursive function to accuse the occurrence of an element in a matrix

Asked

Viewed 91 times

0

I have some problems creating a recursive function that accuses the occurrence of a requested element. So far, this is what I’ve been able to do (perhaps I’ve made some mistake with pointer arithmetic).

#include <stdio.h>
#include <stdlib.h>
#define linhas 2
#define colunas 2

int checainteiro(int matriz[][colunas], int num, int ord)//Retorna 1 caso o numero ocorra, do contrario, retorna 0
{
    int *p;

    p=&matriz[0][0];

    if(*(p+ord-1)==num)
    {
        return 1;
    }
    else if(*(p+ord-1)!=num);
    {
        return (checainteiro(matriz, num, ord-1));
    }
    if(*(p+ord-1)!=num && (ord-1)==0)
    {
        return 0;
    }
}


int main()
{
    int matriz[linhas][colunas];
    int num;
    int i, j;

    printf("\n----Construcao da Matriz----\n\n");
    for(i=0; i<linhas; i++)
    {
        for(j=0; j<colunas; j++)
        {
            printf("Elemento[%d][%d] = ", i, j);
            scanf("%d", &matriz[i][j]);
        }
        printf("\n");
    }

    printf("\n----Construcao da Matriz----\n\n");
    for(i=0; i<linhas; i++)
    {
        for(j=0; j<colunas; j++)
        {
            printf("Elemento[%d][%d] = %d ", i, j, matriz[i][j]);

        }
        printf("\n");
    }



    printf("Digite um inteiro para checar sua ocorrencia na matriz: ");
    scanf("%d", &num);

    if((checainteiro(matriz,num, linhas*colunas))==1)
    {
        printf("O numero %d ocorre na matriz!\n", num);
    }
    else
    {
        printf("O numero nao %d ocorre na matriz!\n", num);
    }

    return 0;
}

1 answer

1


You take this test:

if(*(p+ord-1)==num)

it is obvious that the else will always be (*(p+ord-1)!=num), it is not necessary to make such a test as it will always be true. It turns out that you put a ; right after the condition and therefore will do nothing and execute the next block, which is the recursive call. Your last if will never run and therefore will never return 0.

Try:

int checainteiro(int matriz[][colunas], int num, int ord)//Retorna 1 caso o numero ocorra, do contrario, retorna 0
{
    int *p;

    p=&matriz[0][0];

    if(*(p+ord-1)==num) {
        return 1;
    }
    else if((ord-1)==0) {
        return 0;
    }
    else {
        return (checainteiro(matriz, num, ord-1));
    }
}

Browser other questions tagged

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