How to implement the two sum algorithm to find two values in array that add up to target with C

2 Answers

0 votes
#include <stdio.h>

void twoSum(int array[], int size, int target) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = i + 1; j < size; j++) {
            if (array[i] + array[j] == target) {
                printf("indexes: %d, %d\n", i, j);
                return;
            }
        }
    }
    printf("No solution found.\n");
}

int main() {
    int array[] = { 1, 5, 7, 6, 4, 3, 2 };
    int target = 9;

    int size = sizeof(array) / sizeof(array[0]);
    
    twoSum(array, size, target);

    return 0;
}




/*
run:

indexes: 1, 4

*/

 



answered Jul 17, 2023 by avibootz
0 votes
#include <stdio.h>

void twoSum(int array[], int size, int target, int *pi1, int *pi2) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = i + 1; j < size; j++) {
            if (array[i] + array[j] == target) {
                *pi1 = i;
                *pi2 = j;
                return;
            }
        }
    }
    printf("No solution found.\n");
}

int main() {
    int array[] = { 1, 5, 7, 6, 4, 3, 2 };
    int target = 9, i1 = -1, i2 = -1;

    int size = sizeof(array) / sizeof(array[0]);
    
    twoSum(array, size, target, &i1, &i2);

    printf("%d %d", i1, i2);

    return 0;
}




/*
run:

1 4

*/

 



answered Jul 17, 2023 by avibootz
...