Which of the following correctly implements iterative code for finding power of a number?

Which of the following correctly implements iterative code for finding power of a number?
A.
Code:
#include <stdio.h> 
int power(int x,  int y) 
{ 
    int res = 1;   
    while (y > 0) 
    { 
        if (y & 1) 
            res = res * x;         
        y = y >> 1; 
        x = x * x;  
    } 
    return res; 
} 
int main() 
{ 
    int x = 3; 
    unsigned int y = 5;   
    printf("%d", power(x, y));   
    return 0; 
}
B.
Code:
#include <stdio.h> 
int power(int x,  int y) 
{ 
    int res = 1;   
    while (y > 0) 
    { 
        if (y && 1) 
            res = res * x;         
        y = y >> 1; 
        x = x * x;  
    } 
    return res; 
} 
int main() 
{ 
    int x = 3; 
    unsigned int y = 5;   
    printf("%d", power(x, y));   
    return 0; 
}
C.
Code:
#include <stdio.h> 
int power(int x,  int y) 
{ 
    int res = 1;   
    while (y > 0) 
    { 
        if (y && 1) 
        res = x * x;         
        y = y >> 1; 
        x = x * y;  
    } 
    return res; 
} 
int main() 
{ 
    int x = 3; 
    unsigned int y = 5;   
    printf("%d", power(x, y));   
    return 0; 
}
D.
Code:
#include <stdio.h> 
int power(int x,  int y) 
{ 
    int res = 1;   
    while (y > 0) 
    { 
        if (y & 1) 
        res = x * x;         
        y = y >> 1; 
        x = x * y;  
    } 
    return res; 
} 
int main() 
{ 
    int x = 3; 
    unsigned int y = 5;  
    printf("%d", power(x, y));   
    return 0; 
}
 

Tìm kiếm

Back
Top