Assign it values using loops such that the first element is 3 and every element
ID: 3680078 • Letter: A
Question
Assign it values using loops such that the first element is 3 and every element after that is the determined by the following formula a[i] = a[i-1] + (3*i) if a [i-1] is even number a[i] = a[i-1] - (2*i) if a [i-1] is an odd number 2. Print array elements with each element separated by a space 3. Compute and print the following (with formats given in double quotes): a. average of all array elements - "Average : " (value) b. maximum element - "Maximum value : " (value) c. minimum element - 'Minimum value ; " (value) d. number of elements divisible by 5 - "count of numbers divisible by 5 : " (value)Explanation / Answer
1) Printing of elements with elements startting 3
#include <iostream>
using namespace std;
int main()
{
int a[20];
a[0]=3;
int i;
for ( i = 1; i < 20; i++ )
if ((a[i-1])%2==0){
a[i] = a[i-1]+ (3*i) ;
}else {
a[i] = a[i-1] - (2*i);
}
for ( i = 0; i < 20; i++ )
cout << a[i] << ' ';
return 0;
}
2) Printing elements with space
#include <iostream>
using namespace std;
int main()
{
int a[20];
a[0]=3;
int i;
for ( i = 1; i < 20; i++ )
if ((a[i-1])%2==0){
a[i] = a[i-1]+ (3*i) ;
}else {
a[i] = a[i-1] - (2*i);
}
for ( i = 0; i < 20; i++ )
cout << a[i] << " ";
return 0;
}
3)
a. To find the average of all array elements
#include <iostream>
using namespace std;
int main()
{
int a[20];
a[0]=3;
int i;
for ( i = 1; i < 20; i++ )
if ((a[i-1])%2==0){
a[i] = a[i-1]+ (3*i) ;
}else {
a[i] = a[i-1] - (2*i);
}
for ( i = 0; i < 20; i++ )
cout << a[i] << " ";
float sum = 0.0, average;
sum+=a[i];
average=sum/20;
cout << ' ' << "Average : " << average;
return 0;
}
b. To find the maximum element
#include <iostream>
using namespace std;
int main()
{
int a[20];
a[0]=3;
int i;
for ( i = 1; i < 20; i++ )
if ((a[i-1])%2==0){
a[i] = a[i-1]+ (3*i) ;
}else {
a[i] = a[i-1] - (2*i);
}
if(a[0]<a[i])
a[0]=a[i];
cout << "Maximum Value : " << a[0] << ' ';
for ( i = 0; i < 20; i++ )
cout << a[i] << " ";
return 0;
}
c. To find the Minimum value
#include <iostream>
using namespace std;
int main()
{
int a[20];
a[0]=3;
int i;
for ( i = 1; i < 20; i++ )
if ((a[i-1])%2==0){
a[i] = a[i-1]+ (3*i) ;
}else {
a[i] = a[i-1] - (2*i);
}
if(a[0]<a[i])
a[0]=a[i];
cout << "Minimum Value : " << a[i] << ' ';
for ( i = 0; i < 20; i++ )
cout << a[i] << " ";
return 0;
}
d. Count of numbers divisible by 5
#include <iostream>
using namespace std;
int main()
{
int a[20];
a[0]=3;
int i,count =0;
for ( i = 1; i < 20; i++ )
if ((a[i-1])%2==0){
a[i] = a[i-1]+ (3*i) ;
}else {
a[i] = a[i-1] - (2*i);
}
if(a[i]%5==0)
count = count++;
cout << "Count of numbers divisible by 5 : " << count << ' ';
for ( i = 0; i < 20; i++ )
cout << a[i] << " ";
return 0;
}