Home > Back-end >  C Programming How to get results of an mathematical operation stored in a different array?
C Programming How to get results of an mathematical operation stored in a different array?

Time:08-03

I am trying to subtract a given number from an array and then store the results in a completely different array. Is it possible to write the code without using pointers?

I am trying to write the code with using for loop and or do/while loop.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int main(){

    int num[100];
    int i ;
    int size;
    int sub;
    int diff[100];

    printf("Enter the size of the array: ");
    scanf("%d", &size);
    for(i=0;i<size; i  ){
        printf("Enter the  element %d :", i 1);
        scanf("%d", &num[i]);
    }
    printf(" Enter the number to substract: \n");
    scanf("%d", &sub);

    for (i=0;i<size; i  )
    {
        y = num[i]- sub;
        scanf("%d", &diff[y]);
    }

    for (y=0; y<size; y  )
    {
        printf("%d", diff[y]);
    }
}

After I scan the results, I tried different ways to initialize and store the values in the second array but haven't been successful. What mistake am I making here?

CodePudding user response:

y = num[i] - sub;

This is fine, as it's the result of subtraction for a given source array element.

scanf("%d", &diff[y]);

This doesn't make sense, as it's attempting to read input from the user. Not only that, it's using the result of the subtraction as the index of the destination array.

Just assign the result of the subtraction to the corresponding destination array member:

diff[i] = num[i] - sub;

CodePudding user response:

In your question, you try to scan the value to another array, but the correct form is to assign the value in the new array position.

For example, in your first for loop use the i variable as the position and assign num[i] - sub on diff[i]:

for (i = 0; i < size; i  )
{
    diff[i] = num[i] - sub;
}

instead of:

for (i=0;i<size; i  )
{

    y = num[i]- sub;

    scanf("%d", &diff[y]);
}
  • Related