Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

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
...