In: Computer Science
Write a program in c++ using only while and for loops . Use of arrays and functions is not allowed.
Given the first value, generate the next ten terms of the
sequence like 1, 2, 4, 8, 16, 22, 26,
38, 62, 74, 102, 104, …
Explaination with code is required.
C++ code
#include <iostream>
using namespace std;
int main() {
int start ;
//takes the starting number of sequence
cout<<" Enter the first term of sequence
"<<endl;
cin>>start;
int i ;
//for loop as prescribed to use
for( i = 0 ; i < 10 ; i++ ){
//storing the element
int prev = start ;
//printing the newly calculated
element of sequence
cout<< start << ",
";
int add = 1;
//while loop as prescribed to
use
//logic
// adding the number and the
product of non-zero digits
while( start != 0 ){
//checking if
the digit is zero or not
int r =
start%10;
if( r != 0
){
//so that this is the new value to add into
element
add *= r;
}
//parsing every
digit
start =
start/10;
}
//adding new value to the element
and getting new element of sequence
start = prev + add ;
}
//end of for loop
return 0;
}
Output
74 as first term
Enter the first term of sequence 74, 102, 104, 108, 116, 122, 126, 138, 162, 174,
1 as first term
Enter the first term of sequence 1, 2, 4, 8, 16, 22, 26, 38, 62, 74,
202 as first term
Enter the first term of sequence 202, 206, 218, 234, 258, 338, 410, 414, 430, 442,