#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0

    Explain program line


    Hello. I need to write a program which combines two arrays of n(<=20) elements by using the relations: a[i]=a[i]+b[i],
    b[i]=a[i]*b[i].

    Initially I wrote the program like this:

    Code:
    #include <stdio.h>
    int main()
    {
     int n,a[20],b[20],i;
     printf("Enter number of elements: "); scanf("%d", &n);
     printf("Enter number of elements for a:\n");
     for(i=0; i<n; i++)
     scanf("%d", &a[i]);
     printf("Enter number of elements for b:\n");
     for(i=0; i<n; i++)
     scanf("%d", &b[i]); // read arrays a and b
     
     for(i=0; i<n; i++) // SECOND FOR
     {
      a[i]=a[i]+b[i];
      b[i]=a[i]*b[i];         
     }
     
     printf("Array a is:\n");
     for(i=0; i<n; i++)
     printf("%d ", a[i]);
     
     printf("\nArray b is:\n");
     for(i=0; i<n; i++)
     printf("%d ", b[i]);
     
     getch();
     return 0;
    }
    But in my book says I need to store the a[i] into an aux variable in the first for otherwise the program won't function properly and I don't really understand why. Thank you for reading.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0
    I got it :)
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    India
    Posts
    95
    Rep Power
    4
    Code:
     a[i]=a[i]+b[i];
      b[i]=a[i]*b[i];
    in first line u r changing value of a[i] to a[i]+b[i]
    so when u will use a[i] in 2nd line at that time a[i] will be a[i]+b[i].
    so to use it 2nd time u have to store a[i] in temp. variable.

    or another solution is that use
    Code:
    b[i]=(a[i]-b[i])*b[i]
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    India
    Posts
    95
    Rep Power
    4
    Originally Posted by Cantafford
    I got it :)
    thats good that u got it by yourself :)
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0
    Originally Posted by eramit2010
    thats good that u got it by yourself :)
    The book helped me cudos anyway.

IMN logo majestic logo threadwatch logo seochat tools logo