What is Two Sum in C?
In this post, I am going to write a program in c to find two sum. Now the question is what is two sum?
Also Read: Switch Case in C Program to Calculate Area of Circle and Triangle
In this program, we will read an array from the user. After reading this array, we will read one number, say target. So the two sum is nothing but find the sum of two indices from the array and compare it with the value of the target. If both the values are equal then these two indices values are our output.
Also Read: C Program to Print Multiples of 5 using do-while loop
Maybe you have not understood it very well. Let us see the three expected outputs.
Output 1

As you can see from the above output, the target value is 9. So we need to find indices of two numbers from the array where we get the sum = 9. Here are two numbers i.e. 2 and 7 whose indices are 0 and 1. Therefore, our output is 0 and 1.
Also Read: C Program to Remove Zeros from a number
Let us see the other two outputs with different array elements.
Output 2

Also Read: The while loop in C Programming
Output 3

Now, let us see the actual c program for the above outputs.
Two Sum in C Programming with Solution
#include <stdio.h> #include <stdlib.h> int main() { int nums[100],i,j,size,target,sum=0; printf("Enter the size of an array\n"); scanf("%d",&size); printf("Enter an array elements\n"); for(i=0;i<size;i++) { scanf("%d",&nums[i]); } printf("Enter the value for target\n"); scanf("%d",&target); for(i=0;i<size;i++) { for(j=i+1;j<size;j++) { sum=nums[i]+nums[j]; if(sum==target) { printf("Output : [%d, %d]",i,j); } } } return 0; }
This program can be written in different ways. But I have made it so simple. I hope you have liked it. If you need an explanation of this program, kindly let me know. I will do it for you.
Thank you.
Some Important C Programs
- Program in C to Find Longest Line in a File
- Palindrome in C using Pointers
- Insert and Delete element in Array in C using switch case
- C Program to Add Alternate Elements of a 2D Array
- Arrays in C for Complete Beginners
- C Program to Find Area of a Circle using Preprocessor
- Program in C to Remove White Spaces and Comments from a File
- C Program to Print Numbers Except Multiples of n
- Reverse a Number using getchar and putchar function in c
- The while loop in C Programming