C++ IBM -EDX Lab : Make a Number
Here is one of the lab exercises from the C++ class. The EDX course is run by IBM. I have included my code below the bottom.
Lab: Make a Number
Mark gets n numbers in an array. Write a program considering only the
single digit even numbers in the array and make a number by combining those
even numbers alone.
If there are no single digit even numbers found in an array, then display
the output message as “Single digit even number is not found in the
array”. If the array size is zero or lesser, then display the output
message as “Invalid array size”.
Implement the following methods.
Implement ‘main’: In this
method, get the input by the user and store it in an array. Check if the given
number in an array is having a single digit even number. Implement the logic by
considering only the single digit even numbers.
For example:
Consider an input value {2,7,41,4} stored in an array. In the given
array, get the single digit even numbers which are 2 and 4. Implement a logic
using these even numbers, such that the output is 24.
Note: Please avoid the usage of exit(0) in
your code.
Sample Input 1:
Enter the size of an array:
4
Enter the array elements:
45
4
56
8
Sample Output 1:
48
Sample Input 2:
Enter the size of an array:
0
Sample Output 2:
Invalid array size
Sample Input 3:
Enter the size of an array:
4
Enter the array elements:
3
9
10
29
Sample Output 3:
Single digit even number is not found in the array
My C++ Code (score 100/100):
#include <iostream>
#include <string>
using namespace std;
int main()
{
int array_len;
cout << "Enter the
size of an array:";
cin >> array_len;
if (array_len <= 0){
cout <<
"Invalid array size" <<endl;
}
else {
int digits[array_len];
string s1, value;
cout << "Enter
the array elements:" << endl;
for (int i = 0; i <
array_len; i++){
cin >>
digits[i];
}
for (int j = 0; j <
array_len; j++ ){
if (digits[j] % 2 ==
0 && digits[j] < 10){
s1 = to_string(digits[j]);
value += s1;
}
}
if (value ==
""){
cout <<
"Single digit even number is not found in the array";
}
else{
int val_out =
stoi(value);
cout << val_out;
}
}
Comments
Post a Comment