Home »
C++ programs
Sum of all the elements in an array divisible by a given number K
Here, we are going to learn how to find the sum of the elements in an array which is divisible by a number K?
Submitted by Indrajeet Das, on November 03, 2018
This program will help to find out the sum of elements in an array which is divisible by a number K. It uses the basic concept of modulo '%' or the remainder of a number.
Program:
#include<iostream>
using namespace std;
int main(){
int n, ele;
cout<<"Enter the size of the array.\n";
cin>>n;
int A[n];
cout<<"Enter elements in the array\n";
for(int i =0;i<n;i++){
cin>>A[i];
}
cout<<"Enter the element to be divisible by.\n";
cin>>ele;
int sum = 0;
for(int i =0;i<n;i++){
if(A[i]%ele==0){
sum += A[i];
}
}
cout<<"The sum is "<<sum<<endl;
return 0;
}
Output
Enter the size of the array.
6
Enter elements in the array
2 3 4 5 6 7
Enter the element to be divisible by.
3
The sum is 9