Home > OS >  Put a sequence inside an array in C
Put a sequence inside an array in C

Time:08-27

I'm doing this exercise where I need to show to the user a list of sequence from 1 to 1000 and I have to make:

  • A1=1
  • A2=(A1 4) (A1-2), which is 2*A1 2

But I'm having a few troubles here where it doesn't shows me the numbers being inserted in my list (array)... It only displays me a "0". What am I doing wrong here? Can't find it... Thanks.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i;
    float a;
    float array[1000] = {1};

    a = 1;
    for (i = 0; i <= 1000; i  ) {
        array[i 1] = 2 * a   (a   1);
        printf("\nSequencia:%d - %.2f", i, array);
    }

    system("pause");
    return 0;
}

CodePudding user response:

Use BUFFER_SIZE macro to not overflow because of your condition "i <= 1000", array[1000] is between 0 and 999, your code :array[i 1], will overflow at array[1000] and array[1001].

You are printing array and not array[index].

#include<stdio.h>
#include<stdlib.h>

#define BUFFER_SIZE 1000

int main(void)
{
    float a = 1;
    float array[BUFFER_SIZE] = {1};

    printf("\nSequencia: %d - %.2f", 0, array[0]);
    for (int i = 1; i < (BUFFER_SIZE - 1); i  ) {
        //Maybe you are looking for :  a = 2 * a   (a   1);
        array[i] = 2 * a   (a   1); //Then : array[i] = a;
        printf("\nSequencia: %d - %.2f", i, array[i]);
    }
    system("pause");
        return 0;
}

You may not be able to print everything with float, so you should use bigger types as double or long double.

Doing my best with my english level sorry ^^.

CodePudding user response:

  • You access more elements of the array than the array has.
  • You use a instead of the correct value.
  • The calculation is entirely different than one you said it should be.
  • You print array instead of array[i].

Enable your compiler's warnings!!! It would have caught some of these.

Fixed:

size_t n = 1000;

float array[n];

array[0] = 1;
printf( "%zu - %f\n", 0   1, array[ 0 ] );

for ( size_t i = 1; i < n;   i ) {
   array[ i ] = 2 * array[ i - 1 ]   2;
   printf( "%zu - %f\n", i   1, array[ i ] );
}

There's a final problem: The 1000th number of the sequence will be extremely large. Given a[i]=2*a[i-1], the 1000th number would be 2999. You have a[i]=2*a[i-1] 2 which is even larger. These are huge numbers. For comparison, there are about 1080 ≈ 2266 atoms in the visible universe.

So huge, in fact, that numbers that large can't be stored in a float on an x86 or x86-64. Moving to larger type could help, but it won't give the precision needed. Therefore, you'll need an arbitrary precision library.

  • Related