Computer Science, asked by crackercasperpricky, 2 months ago

Write an indexed for loop to fill an array prime such that element prime[0] contains the first prime number, prime[1] the second prime number, and soon. The prime numbers will be provided as data. Also, write a loop that calculates the sum of all the prime numbers stored.​

Answers

Answered by dreamrob
2

Program in C++:

#include<iostream>

using namespace std;

bool prime(int n)

{

int f = 0;

for(int i = 2 ; i < n ; i++)

{

 if(n % i == 0)

 {

  f = 1;

  break;

 }

}

if(f == 0)

{

 return true;

}

else

{

 return false;

}

}

int main()

{

int n;

cout<<"Enter total number of elements in the array : ";

cin>>n;

int Prime[n];

int count = 0;

int ele = 2;

while(count < n)

{

 if(prime(ele) == true)

 {

  Prime[count] = ele;

  count++;  

 }

 ele++;

}

int sum = 0;

for(int i = 0 ; i < n ; i++)

{

 sum = sum + Prime[i];

}

cout<<"Prime numbers are : ";

for(int i = 0 ; i < n ; i++)

{

 cout<<Prime[i]<<"\t";

}

cout<<"\nSum = "<<sum;

return 0;

}

Output:

Enter total number of elements in the array : 5

Prime numbers are : 2   3       5       7       11

Sum = 28

Similar questions