0

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......

user3238099
  • 21
  • 1
  • 2
  • you need to write what the program outputs so we can provide direct feedback. The while loop itself is properly formatted BTW but may not give you the correct output. – La-comadreja Jan 30 '14 at 21:23
  • So you should grab pen and paper and work out an algorithm. Then, you can try to translate it in C and if you happen to be stuck somewhere, feel free to come here and ask. But don't expect SO users to code that for you. If you already know what you would like to code in C, then edit the question and write it in plain English, so that we can discuss you issue. – Stefano Sanfilippo Jan 30 '14 at 21:24
  • 4
    `2^n` is *not* 2 to the power n. Use the pow function defined in math.h or bit shift (`1 << n`) – Sinkingpoint Jan 30 '14 at 21:25
  • 1
    @Quirliom `pow` will approximate large powers because of floating point. `1 << n` is much better in this specific case. – Stefano Sanfilippo Jan 30 '14 at 21:26
  • 1
    @Quirliom Avoid `pow()`. See http://stackoverflow.com/questions/21452711/pow-seems-to-be-out-by-one-here/21466701 – chux - Reinstate Monica Jan 30 '14 at 22:03
  • `printf("%d\n", (int)log2(n));` – heijp06 Aug 17 '14 at 19:54

2 Answers2

1

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.

abelenky
  • 63,815
  • 23
  • 109
  • 159
0
  1. 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);
    
Ahmed
  • 59
  • 7