0

I've created an array named a that can hold 100 double values,

double a[100];

I set the first element of the array a to NUM, which is a symbolic constant defined early in my code.

a[0] = NUM

I'm curious as to how I would write a for loop that sets each remaining value of a to the value of the preceding element plus 0.1. For example, the second element in the array is the first plus 0.1. I've tried doing

for(i=1; i<=99; i=+0.1)

But I think something is wrong with my initialization of i

1
  • You need to learn how for loops work. Commented May 8, 2014 at 18:05

4 Answers 4

2

Use i to index the array, not to store the value you should put on the array. Remember you can use expressions to access the array, like a[i - 1]

for (i = 1; i < 100; i++)
    a[i] = a[i - 1] + 0.1;
Sign up to request clarification or add additional context in comments.

Comments

1
int i;    
for(i = 0; i < 100; i++)
       a[i] = NUM + 0.1 * i;

dont forget to tell the type int !

1 Comment

You are not allowed to declare the int in the loop. It must be declared before.
0
int i = 0;

for(i = 0; i < 100; i++){
    if (i == 0)
        a[i] = NUM;
    else
        a[i] = a[i - 1] + .1;
}

Your array definition includes the step. So your array would run about 1000 times, at 1, 1.1, 1.2, but a[1.1] isn't a valid index of your array. Use i to index the array, and then retrieve the previous value to set the next.

2 Comments

a[0] = NUM; for (i = 1...) and save yourself the repeated/pointless if() test.
That would be more efficient, but I chose to be more explicit/verbose for the example.
0

From your question I can understand that this is one of your first program in C/C++, so I think that you need to start from basic things and learn how to do it properly, before doing it elegantly.

http://ideone.com/RGZgXL

 for(i = 0; i < ARRAY_SIZE; i++) {
     if(i == 0) { // if we are on the first element, set it to NUM
         array[i] = NUM;
     } else { // otherwise make the sum
         array[i] = array[i-1] + STEP;
     }
 }

In the link you'll find the code and some comments that I hope will help you in understanding it.

Cheers

2 Comments

They should set array[0] first and then loop starting from i = 1; otherwise you end up with a pointless branch in your loop.
Yes I know it. But in this way the code i more clear because respect how he has described the problem. After that he will be able to fix it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.