In: Computer Science
1. Write a C++ program, for.cpp, that reads three integers. The first two specify a range, call them bottom and top, and the other gives a step value. The program should print four sequences using for loops:
Each value in the range from bottom to top
Each value in the range from top to bottom, reverse counting
Every second value in the range from bottom to top
Every value from bottom to top increasing by step
a: If bottom is less than top when entered, the program will
exchange the two values.
b: If step is negative, the program will be set to its absolute
value (positive equivalent).
Sample Run 1 (should have same text and spacing as in examples):
Enter the bottom value in the range: 3 Enter the top value in the range: 20 Enter the step value: 6
Values from 3 to 20:
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Values from 20 to 3:
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3
Every second value from 3 to 20: 3 5 7 9 11 13 15 17 19
Every 6th value from 3 to 20: 3 9 15
Sample Run 2 (demonstrating part a and b):
Enter the bottom value in the range: 72 Enter the top value in the range: 56 Enter the step value: -4
Values from 56 to 72:
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
Values from 72 to 56:
72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56
Every second value from 56 to 72: 56 58 60 62 64 66 68 70 72
Every 4th value from 56 to 72: 56 60 64 68 72
#include <bits/stdc++.h>
using namespace std;
int main()
{
int bottom,top,step;
cout<<"Enter the bottom value in the range: ";
cin>>bottom;
cout<<"Enter the top value in the range: ";
cin>>top;
cout<<" Enter the step value: ";
cin>>step;
step=abs(step);
if(bottom>top)
{
int temp=top;
top=bottom;
bottom=temp;
}
cout<<"Values from "<<bottom<<" to
"<<top<<endl;
for(int i=bottom;i<=top;i++)
{
cout<<i<<" ";
}
cout<<endl;
cout<<"Values from "<<top<<" to
"<<bottom<<endl;
for(int i=top;i>=bottom;i--)
{
cout<<i<<" ";
}
cout<<endl;
cout<<"Every second value from "<<bottom<<" to
"<<top<<endl;;
for(int i=bottom;i<=top;i=i+2)
{
cout<<i<<" ";
}
cout<<endl;
cout<<"Every "<<step<<"th value from
"<<bottom<<" to "<<top<<endl;
for(int i=bottom;i<=top;i=i+step)
{
cout<<i<<" ";
}
cout<<endl;
return 0;
}