Reputation: 19
Q. Write a program that reads a positive integer and then finds the smallest power of 2 that is greater than or equal to the number that was read. For example, if the program reads the value of 25, it should note that 32 = 2^5 is the smallest power of two greater than or equal to 25.
My approach:
**
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1, n;
int num2 = 2^n;
printf("Please type in num1: ");
scanf("%d", &num1);
n = 0;
while (num1 > num2)
{
n=n+1;
}
printf("The power value is %d", n);
return (0);
}
** I am still a beginner so......
Upvotes: 0
Views: 699
Reputation: 59
try this is algorithm is fast
int a, b = 1;
printf("Enter no \n");
scanf("%d",&a);
while (a >= b)
{
b = b << 1 ;
}
printf("%d",b);
Upvotes: 0
Reputation: 64730
When your loop starts, num1
has some specific value, and num2
has another value.
Everytime through the loop, you do not change either value.
So the expression will stay true forever, and the loop will keep running forever, never exiting!
If you want the loop to end eventually, you must change the expression of the loop in some way!
You should modify the value of num1
or num2
inside your loop.
Upvotes: 1