Output range with increment of 5
Mar 6, 2022 at 6:47am UTC
Problem:
Write a program whose input is two integers, and whose output is the first integer and subsequent increments of 5 as long as the value is less than or equal to the second integer.
If input is:
-15 10
The output is:
-15 -10 -5 0 5 10
----
Issue:
Can only output the first integer...
Current Code's Output:
-15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
using namespace std;
int main() {
int input1;
int input2;
cin >> input1;
cin >> input2;
if (input2 < input1){
cout << "Second integer can't be less than the first." ;
}
else {
if (input1 != input2){
cout << input1;
input1 = input1 + 5;
cout << " " ;
}
if (input1 == input2){
cout << input1<< endl;
}
}
return 0;
}
Last edited on Mar 6, 2022 at 6:53am UTC
Mar 6, 2022 at 9:10am UTC
You want a loop, if you want something to happen more than once.
Mar 6, 2022 at 10:42am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main() {
int input1 {}, input2 {};
std::cin >> input1 >> input2;
if (input2 < input1)
return (std::cout << "Second integer can't be less than the first.\n" ), 1;
for (; input1 <= input2; input1 += 5)
std::cout << input1 << ' ' ;
std::cout << '\n' ;
}
Mar 8, 2022 at 2:47am UTC
Fixed program w/ loop + bool:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
using namespace std;
int main() {
int input1;
int input2;
bool isInput2 = false ;
cin >> input1;
cin >> input2;
if (input2 < input1){
cout << "Second integer can't be less than the first." ;
}
else {
while (input1 <= input2){
if (input1 != input2){
isInput2 = false ;
if (isInput2 == false ){
cout << input1 << " " ;
input1 = input1 + 5;
cin >> input1;
}
if (isInput2 == true ){
cout << input1 << endl;
}
}
}
return 0;
}
Last edited on Mar 8, 2022 at 2:49am UTC
Topic archived. No new replies allowed.