Skip to main content

C++ = Code to find sum, product and average of particular numbers

Q2: Create a C++ program that does the following
a. Declare an array of integers with a size of 10 and initialize it with some values
b. Find and display the sum of all even numbers in the array.
c. Find and display the product of all odd numbers in the array.
d. Determine and display the average of all numbers in the array.

Code:

#include <iostream>

using namespace std;

int main()

{

int array[]={1,2,3,4,5,6,7,8,9,10},seven=0,sodd=1,saverage=0;

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

{

if (array[i]%2==0)

{

seven+=array[i];

}

else

{

sodd*=array[i];

}

saverage+=array[i];

}

float average;

average=saverage/10;


cout<<"Sum of even numbers in array is "<<seven<<endl;

    cout<<"Product of odd numbers in array is "<<sodd<<endl;

    cout<<"The average of these numbers is "<<average<<endl;

}

Result:



Comments

Popular posts from this blog

C++ = Code to check number is a prime or not. If not find the nearest prime number.

Code:  #include <iostream> using namespace std; bool prime(int n) { if (n<=1) { return false; }        for (int i=2;i<=n/2;i++)    {       if (n%i==0)   {   return false;   }    }         return true; } int nearest(int n) { for (int i=n-1;i>=2;i--) { if (prime(i)) { return i; } } return 0; } int main () { int number; cout<<"Enter any number : "; cin>>number; if (prime(number)) { cout<<"The number is prime. "<<endl; }     else     {     cout<<"The entered number is compositive."<<endl;     cout<<"The nearest prime number will be "<<nearest(number)<<endl; } } Result:

C++ = Printing diamond with asterik

 CODE: #include <iostream> using namespace std; int main() {     for (int i=1;i<=5;i++)     {     for (int j=1;j<=5-i;j++)     {     cout<<" "; }     for (int k=1;k<=(2*i)-1;k++)     {     cout<<"*"; }   cout<<endl; } for (int i=4;i>=1;i--)     { for (int j=1;j<=5-i;j++)     {     cout<<" "; }     for (int k=1;k<=(2*i)-1;k++)     {     cout<<"*"; }        cout<<endl; } return 0; } RESULT:

C++ = How to sum of digits of any number code.

Code no: 1 = By using array.  #include <iostream> using namespace std; int main()  { int number; cout<<"Enter the n"; cin>>number; int a[number]; int sum=0; cout<<"Enter a digit : "<<endl; for (int i=1;i<=number;i++) { cin>>a[i]; } for (int i=1;i<=number;i++) { sum+=a[i]; } cout<<"The sum of the number : "<<sum; return 0; } Result: Code no: 2 = By using some logic without using array and all the code is in one function. #include <iostream> using namespace std; int main() { int num,origional,sum=0,digit=0; origional=num; cout<<"Enter any no: to finds its sum = "; cin>>num; while(num!=0) { digit=num%10; sum+=digit;  num/=10;  } cout<<"The sum of the digits is "<<sum; return 0; } Result: Code no: 3 = Using same code as of code no: second but using different function to perform same ta...