Skip to content
Home » C program to print sum of the least two numbers in an array

C program to print sum of the least two numbers in an array

Below is the program to print sum of the two least integers in an array

#include <stdio.h>
int main() {
    int n,i,j,k;
    printf("Enter how many numbers do you want to enter:");
    scanf("%d",&n);
    int arr[n];
    printf("Enter elements: ");
    for(i=0;i<n;i++){
        scanf("%d",&arr[i]);
    }
    printf("Elements in the array are:\n");
    for(i=0;i<n;i++){
        printf("%d\n",arr[i]);
    }
    int m1,m2;
    m1=m2=999999;
    for(i=0;i<n;i++){
        if(arr[i]<m1){
            m2 = m1;
            m1=arr[i];
        }
        else if (arr[i] < m2) {
            m2 = arr[i]; 
        }
    }
    printf("Sum of two least numbers is %d",m1+m2);
}

Output:

Enter how many numbers do you want to enter:7
Enter elements: 1
4
7
2
-6
3
6
Elements in the array are:
1
4
7
2
-6
3
6
Sum of two least numbers is -5