0
/* program to express 2^n in sum of n+1 terms
          such that each term is a power of 2
          using formula-- 2^0 + 2^1...... 2^(n-1) = 2^n - 1  */


#include <stdio.h>
#include <math.h>

int num[];


int power(int n){
    for (int i = 0; i<n; i++){
        num[i+1] = pow(2, i);
    }
    return 0;
}



int main(){
    int n;
    printf("Enter power of 2: ");
    scanf("%d", &n);
    power(n);
    printf("Sum in powers of 2 is: ");
    for(int i=0; i<=n; i++){
        printf("%d ", num[i]);
    }
}

OUTPUT - 0 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 for n = 29

  • 2
    Writing to invalid memory results is Undefined Behaviour. UB means the behaviour is unpredictable. It can give wrong values, it can crash, it can even appear to "work" and any other behaviour. – kaylum Feb 15 '22 at 23:16
  • @kaylum So can this code corrupt something on my system too? – Rachit Abhigyan Feb 15 '22 at 23:28
  • Does `int num[];` compile when it is not the last member of a `struct` (a flexible array member)? – Weather Vane Feb 15 '22 at 23:28
  • @WeatherVane I haven't tried that – Rachit Abhigyan Feb 15 '22 at 23:31
  • UB in general can potentially corrupt something on your system. For example it may cause corrupt data to be written to a file. But in this simple case it is unlikely to do any more than crash the application or get wrong results. – kaylum Feb 15 '22 at 23:32
  • You have: the code you posted has to compile `int num[];` when it not a flexible array member of a `struct`. – Weather Vane Feb 15 '22 at 23:32
  • [Running through a sanitizer](https://godbolt.org/z/7o94rfcvf) will show you this ain't such a hot idea. And note the compiler warning that accompanies it. Treating warnings as errors (always do that), the gore could have been avoided in the first place. – WhozCraig Feb 15 '22 at 23:33
  • 2^0 is 1 not 0. Your output was wrong. Check indices you use which go out of array and also in unset index. Allocate num if you need to save result. – Ptit Xav Feb 16 '22 at 07:34

0 Answers0