An incremental sequence is a series of numbers where each term increases by a fixed value, known as the increment. This type of sequence is commonly used in various applications, such as generating arithmetic progressions, indexing, and time-based calculations. In this article, we will demonstrate how to generate an incremental sequence using C++.
#include <iostream>
#include <vector>
// Function to generate an incremental sequence
std::vector<int> generateIncrementalSequence(int start, int increment, int numberOfTerms) {
std::vector<int> sequence;
int term = start;
for (int i = 0; i < numberOfTerms; ++i) {
sequence.push_back(term);
term += increment;
}
return sequence;
}
int main() {
int start = 1;
int increment = 2;
int numberOfTerms = 10;
std::vector<int> sequence = generateIncrementalSequence(start, increment, numberOfTerms);
std::cout << "Incremental sequence: ";
for (int term : sequence) {
std::cout << term << " ";
}
std::cout << std::endl;
return 0;
}
std::vector<int> generateIncrementalSequence(int start, int increment, int numberOfTerms) {
std::vector<int> sequence;
int term = start;
for (int i = 0; i < numberOfTerms; ++i) {
sequence.push_back(term);
term += increment;
}
return sequence;
}
This function generates an incremental sequence given the starting value, increment, and the number of terms. It initializes the sequence with the starting value and iteratively adds the increment to the current term to generate the next term. Each term is then added to the vector sequence
.
int main() {
int start = 1;
int increment = 2;
int numberOfTerms = 10;
std::vector<int> sequence = generateIncrementalSequence(start, increment, numberOfTerms);
std::cout << "Incremental sequence: ";
for (int term : sequence) {
std::cout << term << " ";
}
std::cout << std::endl;
return 0;
}
In the main
function, we define the starting value, increment, and the number of terms for the incremental sequence. We then call the generateIncrementalSequence
function with these parameters to generate the sequence. Finally, we print the sequence to the console.
When the above code is executed, it produces the following output:
Incremental sequence: 1 3 5 7 9 11 13 15 17 19
This output shows the first ten terms of the incremental sequence starting with 1 and increasing by 2 each time. Each term is generated by adding the increment to the previous term.