#include <iostream>
using namespace std;
int f[33] = {3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54,
57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99};
int b[20] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85,
90, 95, 100};
int main (){
for (int x=100; x >= 1; x-- ){
if (x == f){
cout << "fizz" << endl;
} else {
if(x ==b){
cout << "buzz" << endl;
}else{
if(x==f & x==b){
cout << "fizzbuzz" << endl;
}else{
cout << x << endl;
}
}
}
}
}
I am still learning, so this may not be the best way to solve this problem. I just want to know wahts wrong with this code. Thanks
As others have pointed out, you've precomputed your multiples of 3 and 5 in arrays, but then doing direct comparisons between an int and these arrays - this will always fail (ISO C++ forbids comparison between pointer and integer). If you persist with precomputed arrays, you could use std::find or std::any_of to check if either array contains the current number.
However, you would likely gain more credibility if you also included knowledge of how to determine whether a number is divisible by 3 or 5 in your code, rather than pre-populate the multiples of 3 and 5. This is done with the modulo operator, %. Any number % x will return zero if it is naturally divisible by x.
There's another logical flaw in your code. In order to be divisible by both 3 and 5 (i.e. 15, since 3 and 5 are both primes), you will need to change the order of precedence of your checks such that the check for 15 is done first, otherwise you will never reach the fizbuzz branch (since the 3 and 5 branches would also be hit, instead).
Fizzbuzz is usually done incrementally from 1 to 100, but here's your original 'count down' fizzbuzz rewritten:
for (int x=100; x >= 1; x--){
bool isDiv3 = x % 3 == 0;
bool isDiv5 = x % 5 == 0;
if (isDiv3 && isDiv5){
cout << "fizzbuzz" << endl;
} else if (isDiv5) {
cout << "buzz" << endl;
} else if (isDiv3) {
cout << "fizz" << endl;
} else {
cout << x << endl;
}
}
It's also possible to eliminate one of the if branches, by running the printed fizz and buzz into eachother on a factor of 15, although this isn't necessarily as easy to read:
for (int x=100; x >= 1; x--){
bool isDiv3 = x % 3 == 0;
bool isDiv5 = x % 5 == 0;
if (isDiv3) {
cout << "fizz";
}
if (isDiv5) {
cout << "buzz";
}
if (!isDiv3 && !isDiv5)
cout << x;
}
cout << endl;
}
The error with your code is you can't compare integer and pointer , What you are trying to do is to find if x is in f or if x is in b or both .
But why do yo have to do that , you know the properties governing the sets f and b which are simply "%3==0" , "%5==0" .So you can do something pretty easy like
#include <iostream>
using namespace std;
int main (){
for (int x=100; x >= 1; x-- ){
if(x%3==0) cout<<"Fizz";
if(x%5==0) cout<<"Buzz";
else if(x%3 !=0) cout <<x;
cout<<endl;
}
}
x is an int, while f is an array. You cannot compare them this way:
if (x == f){
If your technique is to check whether x is in the array f, I suggest, you have to check for each value in f, like
if(x == f[i++]){
where i is an index used to traverse the f array.
Also, you might consider evaluating the condition of x in both f and b before their individual evaluation.
x is an integer whereas f and b are arrays of integers. If you want to test membership of the content of your variable x in the arrays f and b you probably want to define your own function to check it.
int is_in(int item, int[] list){
for(i = 0; i < sizeof(list) / sizeof(struct list); i++){
if(item==list[i]) return 1;
}
return 0;
}
And then change your conditions to if(is_in(x,b))
Related
I use this script to print odd number from 1 to 30.
#include <iostream>
using namespace std;
int main( ) {
int i = 1 ;
// whele loop from 1 to 30
while (i <= 30) {
cout << i<< " , ";
i = i + 2;
}
return 0;
}
So the output Will be 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29
What i must to do if i want to add Even number after 4 Odd numbers. The output Will be like 1, 3, 5, 7, 10, 11, 13, 15, 17, 20, 21, 23, 25, 27, 30.
I hope someone can help me with this problem. Thank you
At each iteration you print a number as you are doing now, however, every 5th iterations what you do is a bit different. This is a condition you need to test in each iteration: if true, print like this, if false, print like that.
Start with the loop as you did. Since you using a counting variable that you always increment, a for loop seems more natural than a while.
int main() {
for(int i = 1; i <= 30; i += 2) {
cout << i << " , ";
}
return 0;
}
Now you add the condition test. For that, you can introduce another variable (numOddNumbers) to keep track of how many odd numbers you have printed.
int main() {
int numOddNumbers = 0;
for(int i = 1; i <= 30; i += 2) {
if(numOddNumbers > 0 && numOddNumbers % 4 == 0) {
cout << i + 1 << " , ";
numOddNumbers = 0;
} else {
cout << i << " , ";
numOddNumbers++;
}
}
return 0;
}
For the condition we can use numOddNumbers % 4 == 0 to check that numOddNumbers is amultiple of 4, but since we do not want the condition to be true when numOddNumbers == 0 we also make sure that numOddNumbers > 0.
Notice that differently from i, the numOddNumbers variable is only incremented when the condition is false, since that is when we print an odd number.
This code will print
1 , 3 , 5 , 7 , 10 , 11 , 13 , 15 , 17 , 20 , 21 , 23 , 25 , 27 , 30 ,
Note: An interesting exercise for you is to simplify this code to use just the counting variable, without the extra numOddNumbers variables. The pattern is well defined and you know that the difference is in every 5th itertion.
I can offer the solution of your problem.
#include <iostream>
#include <vector>
using namespace std;
void showContentVector(vector<int>& input)
{
for(int i=0; i<input.size(); ++i)
{
cout<<input[i]<<", ";
}
return;
}
void oddEvenNumbers(int start, int stop, int quantity, vector<int>& input)
{
if(start>stop)
{
return;
}
if(start%2!=0)
{
input.push_back(start);
++quantity;
}
if(quantity==4)
{
start+=3;
input.push_back(start);
quantity=0;
}
oddEvenNumbers(start+1, stop, quantity, input);
return;
}
void solve()
{
vector<int> inputVector;
oddEvenNumbers(0, 30, 0, inputVector);
cout<<"inputVector <- ";
showContentVector(inputVector);
return;
}
int main()
{
solve();
return 0;
}
Here is the result:
inputVector <- 1, 3, 5, 7, 10, 11, 13, 15, 17, 20, 21, 23, 25, 27, 30,
If you will need an explanation of the solution, write the corresponding comment.
#include <iostream>
using namespace std;
int main(void) {
int i = 1;
int step = 1;
while (i <= 30) {
if (step % 5 == 0) {
cout << (i + 1) << ",";
}else{
cout << i << ",";
}
i += 2;
step++;
}
return 0;
}
I'm trying to see if a number is divisible by any given numbers in an array.
I've seen a lot of answers with the number1 % number2 == 0 answer but I haven't found any with an array of numbers and I'd rather not write out each number in the array myself (that would be working too hard).
So here is what I'm trying to figure out. As you can see the only way this works currently is if the last number I give it is true otherwise the else statement kicks in and evaluates number1_result to false.
int square_numbers[10] = { 4, 9, 25, 36, 49, 64, 81, 100, 121, 144 };
int number1;
bool number1_result;
cin >> number1;
for (int i = 0; i < 10; i++) {
if(number1 % square_numbers[i] == 0)
number1_result = true;
else
number1_result = false;
}
How do I make sure that if the loop ever evaluates to true once, it is true. If its not true at least one time, it is false.
Let me know if you need more info and thank you!
Break the loop once you find a divisor.And use = instead of == for assignment. Correct solution is-
int square_numbers[10] = { 4, 9, 25, 36, 49, 64, 81, 100, 121, 144 };
bool number1_result=false;
for (int i = 0; i < 10; i++) {
if(number1 % square_numbers[i] == 0) {
number1_result = true;
break;
}
}
Problem with your code is that it overwrites number_result even if it is already true.
Consider the example, number1=4, square_number={2, 3}
In your loop num_result will become true at first comparison but it will again become false on next comparison with 3.
With std:
bool number1_result = std::any_of(std::begin(square_numbers),
std::end(square_numbers),
[&](auto e){ return number % e == 0; });
The problem is you are assigning number1_result which should check inside the loop but instead you have to input number1:
cin >> number1_result; // redundant
The answer:
int square_numbers[10] = { 4, 9, 25, 36, 49, 64, 81, 100, 121, 144 };
bool number1_result = false;
int number1;
cin >> number1;
for (int i = 0; i < 10; i++) {
if(number1 % square_numbers[i] == 0){
number1_result = true;
break;
}
}
Please help me use C++ to parse an array and only display numbers that are unique. I have written a program which answers most of the question below.
Question:
Use a one-demensional array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, validate and store it in the array only if it isn't a duplicate of a number already read. After reading all the values, display only the unique values that the user entered. Provide for the "worst case" in which all 20 number are different. Use the smallest possible array to solve this problem.
What I've done:
My program creates a 20 item array. Prompts user for data, validates it and displays it. I have tried several way to only display unique data, however I have not accomplished what the question asks.
Sample User Input:
11, 12, 12, 12, 13, 14, 15, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27
My Program Output:
{ 11, 12, 12, 12, 13, 14, 15, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 }
Correct Program Output:
{ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 }
Any advice where to go with this. See below for code. Thank you for your help!
#include <iostream>
#include <array> // needed for c++11 arrays
using namespace std;
int main()
{
const int arraySize = 20; // limit array length to 20
array <int, arraySize userArray> = {};
//Populate array with user input and validate it to be between 10 and 100
for (int i = 0; i < userArray.size(); i++)
{
cout << "Enter a number between 10 and 100" << endl;
cin >> userArray[i]; // get user input assign it to proper array subscript
while(userArray[i] > 100 || userArray[i] < 10)//validate user input to be between 10 and 100
{
cout << "Number needs to be between 10 and 100. Enter a new number" << endl;
cin >> userArray[i]; //reassign the proper array subscript if needed
}
}
cout << endl;
//display the information to look like an array
//result looks like [ v, w, x, y, z ]
cout << "[ ";
//display array values
for (int i = 0; i < userArray.size() - 1; i++)
{
cout << userArray[i] << ", ";
}
//properly display last array item
cout << userArray[(userArray.size() - 1)] << " ]" << endl;
return 0; }
If you can use std::vector, then you can use following solution.
template <typename Type>
std::vector<Type> unique_entries (std::vector<Type> vec) {
for (auto iter = vec.begin (); iter != vec.end (); ++iter) {
auto f = std::find_if (iter+1, vec.end (), [&] (const Type& val) {
return *iter == val; // (X)
});
if (f != vec.end ()) {
vec.erase (std::remove (iter+1, vec.end (), *iter), vec.end ());
}
}
return vec;
}
template <typename T>
void show (std::vector<T> vec) {
for (const auto& v : vec) {
std::cout << v << " ";
}
std::cout << std::endl;
}
And example would be like that:
std::vector<int> vec {11, 12, 12, 12, 13, 14, 15, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27};
std::vector<short> vec2 {1, 1, 1, 2, 3, 2, 1, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 10};
std::vector<std::string> vec3 {"a", "a", "a", "aa", "b", "b", "bb", "c"};
show (vec);
show (unique_entries (vec));
show (vec2);
show (unique_entries (vec2));
show (vec3);
show (unique_entries (vec3));
And the output:
11 12 12 12 13 14 15 15 16 17 18 19 20 21 22 23 24 25 26 27
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
1 1 1 2 3 2 1 2 1 2 3 2 1 2 3 2 1 2 10
1 2 3 10
a a a aa b b bb c
a aa b bb c
Look at the line (X), basically you can use this unique_entries for all types which offer operator==, but you have to keep in mind that this will probably fail if you use this function for floating point types.
Hope this is what you are looking for........... Basically I use an another array to store the elements already entered by the user. So when the user enters a number it checks whether it is already in the array of 'entered elements' or not.
#include<iostream>
#define MAX 20
using namespace std;
int main()
{
int list[MAX],visitedElements[MAX];
int noElements,element,currentIndex;
bool flag=false;
cout<<"Enter total no. of elements(MAX=20):"<<endl;
cin>>noElements;
for(int i=0; i<noElements; i++)
{
visitedElements[i] = -1;
}
for(int i=0;i<noElements;i++)
{
currentIndex=i;
cout<<"Enter Element:"<<endl;
cin>>element;
for(i=0;i<currentIndex;i++)
{
if(visitedElements[i] == element)
{
flag==true;
break;
}
}
if(flag == false)
{
list[i]=element;
visitedElements[i] = element;
}
flag = false;
}
cout<<"Elements in list are"<<endl;
for(int i=0 ; i<noElements ;i++)
cout<<list[i]<<endl;
return 0;
}
#include <iostream>
using namespace std;
int main(){
int tab[10];
int i=0,j;
int number=0;
int counter=1;
bool flag=true;
int tries=0;
while(tries<10){
do{
cin>>number;
tries++;
if((number>100)||(number<10)){
cout<<"Wrong number, has to be between 10 and 100"<<endl;
}
}
while((number>100)||(number<10));
flag=true;
if(i==0){
tab[i]=number;
}
else{
for(j=0; j<counter; j++){
if(tab[j]==number){
flag=false;
i--;
break;
}
}
}
if(flag==true){
tab[i]=number;
counter++;
}
i++;
}
for(i=0; i<counter-1; i++){
cout<<tab[i]<<", ";
}
}
I kinda meesed it up probably. I'm new to programing but this is my solution.
So. You said it has to take 20 digits, mine takes 10, after 10 inputs it will list the array. So if my input is "10, 10, 10, 12, 13, 15, 15, 18, 22, 22"
the output is: "10, 12, 13, 15, 18, 22"
I could probably erase half of the code but like i said I'm a beginner and i was writing it in a hurry.
EDIT: Ups, small mistake in the array declaration. I was testing it for 5 elements and forgot to make a bigger array.
The question asked to use one array, so I would loop over the numbers already in the array after reading in each number and check for duplicates. It would look something like this:
#include <iostream>
constexpr int ARRAY_SIZE = 20;
int main()
{
int userArray[ARRAY_SIZE], validNumbers = 0;
for(int i = 0; i < ARRAY_SIZE; i++)
{
int num;
bool isGood = true;
std::cin >> num;
//code to check if input is in range here
for(int j = 0; j < validNumbers; j++)
{
if(userArray[j] == num)
{
isGood = false;
break;
}
}
if(isGood)
{
userArray[validNumbers] = num;
validNumbers++;
}
}
//userArray now contains all unique numbers in the order that they were entered
for(int i = 0; i < validNumbers; i++)
{
std::cout << userArray[i];
if(i < validNumbers - 1)
{
std::cout << ' ';
}
}
std::cout << '\n';
}
inside of your for loop, instead of makign the cin go directly into the array, add another int variable and set it to equal the input
cin >> variable
then make a for loop that iterates through your current array to make sure its not a duplicate; use the line below as your for loop
for(int j = 0; j < i; j++)
if the number is already in the array, just continue. Else, add it in.
Also, instead of using a for loop in the beginning, I would use a while loop with
while(i < arraysize)
Then deincrement array size every time you see a duplicate and only increment i when you add an element
I understand the array address but this code which I found in a book made me nut.I understand the recursive function too but did not get this one.Here is the code:
int main(){
const int arraySize = 5;
int a[arraySize] = { 32, 27, 64, 18, 95};
cout << "The values in reverse array are:" << endl;
someFunction(a, arraySize);
cout << endl;
cin.get();
return 0;
}
void someFunction(int b[], int size)
{
if (size > 0) {
someFunction(&b[1], size - 1);
cout << b[0] << " ";
}
}
I got this code in a exercise.My question is how it is reversing the array?I will be happy if anyone explain a bit more.thanks
Here is some pseudo-code which shows how the recusive calls to someFunction will be made, and in which order:
someFunction( { 32, 27, 64, 18, 95} , 5)
someFunction( { 27, 64, 18, 95}, 4)
someFunction( { 64, 18, 95}, 3)
someFunction( { 18, 95}, 2)
someFunction( { 95}, 1)
someFunction( { }, 0)
someFunction({ }, 0) will return without doing anything because there is nothing left in the array. Now someFunction will print the first element b[0] of the arrays as it comes out of the recursion, beginning with the array containing only one item {95}:
{ 95 }
{ 18, 95}
{ 64, 18, 95}
{ 27, 64, 18, 95}
{ 32, 27, 64, 18, 95}
So your output will be:
"The values in reverse array are:"
95 18 64 27 32
b[1] is the second element of the array. &b[1] is the address of the second element, so it is just like the original array, but 1 smaller and skipping the first element.
If you print out everything except the first element before you print the first, and do it recursively, the result is it prints out in reverse order.
Note that the actual array has not been reversed. It only gets printed in reverse order. And it's nonsense. A loop is better.
I am new to C++. I am trying to read through the array of numbers and count the amount of numbers in the array that are equal to the user entered number. I am not sure what to do next to get it to make number = number1 and count it. I hope this makes sense. Thanks.
#include <iostream>
using namespace std;
int main()
{
int number[20] = {80, 52, 25, 71, 56, 90, 87, 10, 32, 80, 2, 67, 73, 50, 52, 73, 72, 20, 86, 99};
int numberCount = 0;
int number1 = 0;
cout << "Enter a number between 0 and 100: ";
cin >> number1;
while(number1>100 || number1<0)
{
cout << "Invalid number,enter again" << endl;
cin >> number1;
}
for(i = 0; i < 20; i = i + 1)
{
}
system("pause");
return 0;
}
There's a function in the standard library for this, in the <algorithm> header:
int numberCount = std::count(number, number + 20, number1);
You just need to test whether number1 is equal to each value stored in the array. Using the variable i as an index, which you already have set up in the for loop, you can access the array's values one by one and compare with number1. If they match then you increment the counter variable.
for(i = 0; i < 20; i = i + 1)
{
// the next line tests whether the value of variable `number1` is equal
// to the value stored in the `number` array, at the index `i`
if(number1 == number[i])
{
numberCount += 1; // if there is a match, increment the counter
}
}
Compare each entry in the array 'number[]' against the number supplied by the user 'number1':
for (int i = 0; i < 20; i++)
{
if (number1 == number[i])
{
numberCount++;
}
}