Thinh
Thinh

Reputation: 230

C "for" loop issue

I am running this program

#include <stdio.h>
int main ()
{
  int n;
  int a = 1;
  int b = 2;
  int product;
  int i;

  printf("How many numbers of the sequence would you like \n");
  scanf("%d",&n);

  for (i=0;i<n;i++)
  {
    printf("%d\n",a);
    product = a * b;
    a = b;
    b = product;
  }

   return 0;
}

When I enter n = 3, the result is 1 2 2
Why is it ? I meant to make it so it show 1 2 4 , what have I done wrong ? And why is it print 1 2 2 .

Upvotes: 0

Views: 128

Answers (4)

ameyCU
ameyCU

Reputation: 16607

1 2 2 because you print a not product and value of a in each iteration is -

  1st iteration a=1
  2nd iteration a=2        // a=b and b=2 i.e a=2
  3rd iteration a=2        // why ? because again a=b and b did not change 
  thus output 1 2 2

Simple solution would be -

1.Initialize product to 1 // int product =1;

2.print product instead of printf("%d\n",a); // printf("%d\n",product);

Upvotes: 0

Rahul
Rahul

Reputation: 77846

I meant to make it so it show 1 2 4

Then interchange the below two lines

 a = b;
 b = product;

It should be

for (i=0;i<n;i++)
 {
 printf("%d\n",a);
 product = a * b;
 b = product;
 a = b;
 }

Upvotes: 0

Saiph
Saiph

Reputation: 520

Your code does exactly what it's supposed to do.

Maybe you wanted :

 #include <stdio.h>
 int main ()
 {
 int n;
 int a = 1;
 int b = 2;
 int product;
 int i;

 printf("How many numbers of the sequence would you like \n");
 scanf("%d",&n);

 printf("%d\n",a);

     for (i=1;i<n;i++)
     {
     product = a * b;
     a = b;
     b = product;
     printf("%d\n",b);
     }    

 return 0;
 }

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

And why is it print 1 2 2 .

Step-by-step trace at printf("%d\n",a);:

i  a  b  product
0  1  2  ?
1  2  2  2
2  2  4  4
3  4  8  8
4  8  32 32

Upvotes: 2

Related Questions