Reputation: 75
I am trying to display the multiples of a user-inputted number given 6 user-inputted numbers. I think I am sort of close, but I am stuck.
For example, if someone enters "4" and then their 6-number sequence is "23 45 12 16 51 8", it should return 12 16 8 because those are the multiples of the first inputted "4".
So far I have the following:
#include <iostream>
using namespace std;
//Display multiples of a number that appear within a sequence of numbers.
//E.g. input is looking for multiples of 5 in the following sequence of 6 numbers: 6 10 9 3 25 79 → output: 10 25
int main() {
int userNum;
int seq1, seq2, seq3, seq4, seq5, seq6;
cout << "Enter a number: " << userNum;
cin >> userNum;
cout << "Enter a sequence of 6 numbers: " << seq1 << " " << seq2 << " " << seq3 << " " << seq4 << " " << seq5 << " " << seq6;
cin >> seq1;
cin >> seq2;
cin >> seq3;
cin >> seq4;
cin >> seq5;
cin >> seq6;
int sequence[] = {seq1, seq2, seq3, seq4, seq5, seq6};
int total;
for (int sequence[] = seq1; i < 6; i++) {
if (i % userNum == 0) {
return total;
}
}
cout << "Multiples in the sequence are: " << total;
}
Upvotes: 0
Views: 245
Reputation: 117473
userNum
and seq1
to seq6
before you've assigned values to them. That makes the program have undefined behavior.for
loop has invalid syntax and you also return
instead of printing the matching values. A fix could look like this:
for (int i = 0; i < 6; i++) {
if (sequence[i] % userNum == 0) {
std::cout << sequence[i] << ' ';
}
}
seq1
to seq6
. Just input directly into sequence
. You can also use range-based for loops to make looping over the elements in sequence
easier.Example:
#include <array> // std::size
#include <iostream>
int main() {
int userNum;
std::cout << "Enter a number: ";
std::cin >> userNum;
int sequence[6];
std::cout << "Enter a sequence of " << std::size(sequence) << " numbers: ";
for(int& num : sequence) { // a range-based for loop
std::cin >> num; // assign to all 6 elements in a loop
}
std::cout << "Multiples in the sequence are: ";
for(int num : sequence) { // another range-based for loop
if(num % userNum == 0) {
std::cout << num << ' ';
}
}
std::cout << '\n';
}
Upvotes: 3