I have to find the third and the fifth even element of the array A. But... I don't know why the program isn't working.

+2 votes
asked Nov 19 by Lata (640 points)

This is a part of my code

for(int i=0; i<3; i++){
       for(int j=0; j<4; j++){
           if(A[i][j]%2==0){   
               n++;
           }
           if(n==3){
               p3=A[i][j];
               ip3=i;
               jp3=j;
           }
           if(n==5){
               p5=A[i][j];
               ip5=i;
               jp5=j;
           }
       }
       
And this is the result:
Compilation failed due to following error(s).main.c: In function main’:
main.c:20:22: error: invalid operands to binary % (have float and int’)
            if(A[i][j]%2==0){
               ~~~~~~~^

1 Answer

+2 votes
answered Nov 19 by xDELLx (4,800 points)
selected 6 days ago by Lata
 
Best answer

Can you try below & see if the code works with below change.
Use a temp int variable to store data of the array element & use it in the if condition.

The compiler is complaining because ,I think the definition of A is float A[][].
Implying individual elements are float & using the modulo operator expects both int args.

 


 //...existing code here ie for loops
int temp = A[i][j];
 if(temp%2==0){
 n++;
 }
//...existing code here 
if(n==3){ 
//...
//...
}
if(n==5){ 
//...
//...
}
//...existing code here 

commented 6 days ago by Lata (640 points)
Thank you! I've just changed float array to the int array and now it's all right!
commented 6 days ago by Peter Minarik (12,220 points)
Yes. That's what the error message said: "invalid operands to binary % (have ‘float’ and ‘int’)", that is, you're trying to use the modulo (%) operator on a floating point number. It only works on integral numbers.

Good job! ;)
commented 6 days ago by Lata (640 points)
Thank you! I didn't know that before)
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...