Parth Panwar
Parth Panwar

Reputation: 1

Write a for statement to print -10,-12,-14,-18,-26,-42 using for loop in c

This question should be done using only a for loop. I have tried to make fibonacci series also but then also it is not working and it shows -16 every time after -12. Let me give you the code and please tell me where I am doing it wrong.

int i;
int t1=-10;
for (i==1; i<=5; i++) {
    printf("%d",t1);
    int t2=-2;  
    t1+=(t2*i);
}

Upvotes: 0

Views: 779

Answers (1)

WaitingForGuacamole
WaitingForGuacamole

Reputation: 4301

A few things:

  1. The first argument to your for loop isn't assigning i, it's checking to see if it's non-zero. so, your initial value in the loop for i is 0. If I run your example as written it just exits with no output.
  2. You're bumping up the amount to decrement by 2 after every pass. You want to delay it so that this doesn't happen until after the first pass completes.
  3. The behavior you want is to get 2 to double itself each time (exponential increase), but your loop is multiplying 2 by the index (linear increase)

A version of this that fixes those three issues looks like this:

    int i;
    int t1 = -10;           

    for (i=0; i<=10; i++) {
        printf("%d\n", t1);
        // if i > 0, use i,
        // otherwise use 1 (first time through the loop)
        // so, 1 << 1, then 1, 2, 3, 4, 5, etc.
        // becomes 2, then 2, 4, 8, 16, 32, etc.
        t1 -= 1 << (i ? i : 1);
    }

Upvotes: 1

Related Questions