C ++ PROGRAMMING, Please Answer All. Part 1 a) Create an int array to store 10 v
ID: 3810666 • Letter: C
Question
C ++ PROGRAMMING, Please Answer All.
Part 1
a) Create an int array to store 10 values. Write a simple loop to initialize the array elements with the values 2, 4, ... 20
Write another loop to print all the elements of the array in reverse.
b) Create a char array to store 26 values. Write a simple loop to initialize the array elements with the values a, b, c ... z
Write another loop to print all the vowels and the index where each is stored. e.g.: a at index 0
c) Implement a function named avg that takes an int array and its length as parameters and returns the average of the values in the array.
Call the function with a sample array and print the average value.
d) Implement a function named min_max that takes an int array, its length, and two int parameters min and max. The function sets min to the min value in the array and max to the max value in the array. The function returns nothing. Call the function and print the min and max values found.
Explanation / Answer
Question a
Answer:
#include <iostream>
using namespace std;
int main()
{
int a[10];
for(int i=0, j=2; i<10; i++, j+=2){
a[i] = j;
}
for(int i=9; i>=0; i--){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
20 18 16 14 12 10 8 6 4 2
Question b
Answer:
#include <iostream>
using namespace std;
int main()
{
char ch[26];
for(int j=0,i=97; i<=122;i++,j++){
ch[j] = i;
}
for(int i=0 ; i<26; i++){
if( ch[i] == 'a') {
cout<<"a at index "<<i<<endl;
}
else if( ch[i] == 'e') {
cout<<"e at index "<<i<<endl;
}
else if( ch[i] == 'i') {
cout<<"i at index "<<i<<endl;
}
else if( ch[i] == 'o') {
cout<<"o at index "<<i<<endl;
}
else if( ch[i] == 'u') {
cout<<"u at index "<<i<<endl;
}
}
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
a at index 0
e at index 4
i at index 8
o at index 14
u at index 20
Question c
Answer:
#include <iostream>
using namespace std;
double avg(int array[], int length){
int sum = 0;
for(int i=0; i<length; i++){
sum = sum + array[i];
}
return sum/(double)length;
}
int main()
{
int a[] = {1,2,3,4,5};
cout<<"Average is "<<avg(a, 5)<<endl;
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Average is 3
Question d
Answer:
#include <iostream>
using namespace std;
void min_max(int array[], int length){
int min = array[0];
int max = array[0];
for(int i=0; i<length; i++){
if(max < array[i]){
max = array[i];
}
if(min > array[i]){
min = array[i];
}
}
cout<<"Max is "<<max<<endl;
cout<<"Min is "<<min<<endl;
}
int main()
{
int a[] = {1,2,3,4,5};
min_max(a, 5);
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Max is 5
Min is 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.