Search code examples
c++arraysloopsfor-loopinsert

code not running as expected in VS Code but working in other IDE


#include <stdio.h>
#include <conio.h>

main()
{
    int LA[] = {1, 3, 5, 7, 8};
    int item = 10, k = 3, n = 5;
    int i = 0, j = n;

    printf("The original array elements are :\n");

    for (i = 0; i < n; i++)
    {
        printf("LA[%d] = %d \n", i, LA[i]);
    }

    n = n + 1;

    while (j >= k)
    {
        LA[j + 1] = LA[j];
        j = j - 1;
    }

    LA[k] = item;

    printf("The array elements after insertion :\n");

    for (i = 0; i < n; i++)
    {
        printf("LA[%d] = %d \n", i, LA[i]);
    }
}

I have tried copying the code in other IDEs it worked but is not working in VS Code can someone help me i am new to stackoverflow


Solution

  • For starters there is noting from C++ in your program.

    Your program is a C program.

    At least in C++ the headers should be

    #include <cstdio>
    #include <cconio>
    

    instead of

    #include <stdio.h>
    #include <conio.h>
    

    The array has the fixed size equal to 5. It can not store 6 elements.

    If you want to insert a new value in the array then the value stored in the last element will be lost.

    So these statements

    n = n + 1;
    
    while (j >= k)
    {
        LA[j + 1] = LA[j];
        j = j - 1;
    }
    

    do not make sense and lead to undefined behavior.

    The program can look like

    int a[] = { 1, 3, 5, 7, 8 };
    const size_t N = sizeof( a ) / sizeof( *a );
    
    printf( "The original array elements are: " );
    
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "a[%zu] = %d ", i, a[i] );
    }
    putchar( '\n' );
    
    int item = 10;
    size_t pos = 3;
    
    if ( pos < N )
    {
        for ( size_t i = N; pos < --i; )
        {
            a[i] = a[i-1]; 
        }
        a[pos] = item;
    }
    
    printf( "The array elements after insertion: " );
    
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "a[%zu] = %d ", i, a[i] );
    }
    putchar( '\n' );
    

    Pay attention to that instead of the for loop that moves values of the array to the right you could use C function memmove.

    In C++ you could use standard container std::vector instead of the array.