Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

What I'm missing here?

xanderbilla

New Coder
C:
//Inserting value at the end

#include <stdio.h>

void main()
{
    int i, upper_bound, n, value, arr[10] = {10,20};

    n = sizeof(arr)/sizeof(arr[0]);

    printf("Please give upperbound value: ");
    scanf("%d", &upper_bound);

    for (i = upper_bound+1; upper_bound == n ;i++)
    {
        printf("Please give a number to insert at end: ");
        scanf("%d", &value);
        arr[i] = value;
    }
}
 
Bit of a strange term, inserting at the end. Adding to the end is not inserting but appending. The act of inserting involves moving array element forward to make room, which I don't see happening here. Actually it seems you are just filling the array starting with a specified index.

Anyway, look at the end condition in your for loop : upper_bound == n. This is ether false or true, and never changes (because upper-bound and n do no change). So either you never go into the loop of you go into it but never get out. Either way, not good. You may want to re-think what you are doing there. Didn't you just mean to write i < n instead ? Assuming that upper_bound is less than n. If not your program will likely crash.

It seems unusual to define an array with 10 elements but initialize with only two element. And then calculate the number of elements by using sizeof. Did you check the calculated value of n is 10 as you probably would expect ?

Lastly, at the end of the program, would you not print the entire array to check that everything is correct ?
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom