Home >>Cpp Programs >Sum of all the elements in an array divisible by a given number
In this example, we will see a C++ program through which we get the sum of all the elements in an array divisible by any given number K.
In this program, we will use 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;
}