Write a C++ program that creates two one dimensional arrays “A” and “B” of size 20 elements each. The main
program should get the input in the array “A” from the user and initialize array “B” with values “0”. Your
program should calculate the (number -2) of each element of array “A” and should store in the square value
in corresponding positions (index) in the array “B”. In the end, the main program (main function) prints the
calculated values of array “B”. Also display the values in array B which are Odd (if any).
#include <iostream>
int main() {
const int size = 20;
int A[size], B[size];
for (int i = 0; i < size; ++i) {
B[i] = 0;
}
std::cout << "Enter values for array A, separated with space:\n";
for (int i = 0; i < size; ++i) {
std::cin >> A[i];
B[i] = (A[i] - 2) * (A[i] - 2);
}
std::cout << "Array B:\n";
for (int i = 0; i < size; ++i) {
if (i) std::cout << ' ';
std::cout << B[i];
}
bool foundOdd = false;
for (int i = 0; i < size; ++i) {
if (B[i] % 2) {
if (!foundOdd) {
std::cout << "\nOdd values in array B:\n";
foundOdd = true;
}
else {
std::cout << ' ';
}
std::cout << B[i];
}
}
if (!foundOdd) {
std::cout << "\nThere are no odd values in array B";
}
std::cout << '\n';
return 0;
}
Comments
Leave a comment