I've been tasked to create a function that identifies the number of occurrences in an array, however i am not getting the correct result. This is the function i wrote, i left out the rest of the program as that works.
int countOccurences(int b[], int size, int x)
{
int occ = x;
for(int i = 0; i < size; i++)
{
if(b[i] == occ)
occ++;
}
cout << occ << endl;
return occ;
}
If occ is meant to be the number of occurrences, it should be initialised to zero rather than x.
And the comparison should be between b[i] and x, not b[i] and occ.
And, as an aside (not affecting your actual logic), it's also very unusual to actually print out the return value in a utility function which is obviously meant to simply return the count but it may be you have that in there just for debug purposes.
And you should both ensure your indentation and use of braces is consistent between your for and your if - it will make your code easier to maintain.
That's all totally aside from the fact that C++ possesses a std::count() method in <algorithm> that will work this out for you without having to write a function to do it (although it may be that this is an educational question and the intent is to learn how to code things like this, rather than use readily made library functions to do the heavy lifting for you).
int countOccurences(int b[], const unsigned int size, const int x)
{
int occ = 0;
for(unsigned int i = 0; i < size; i++)
{
if(b[i] == x)
{
occ++;
}
}
std::cout << occ << std::endl;
return occ;
}
occ should start at zero
You should compare b[i] to x
Array indices should be unsigned
Why not be const-correct?
using namespace std; is bad practice
Related
The point of this program is to output whether a series of digits (the number of digits undefined) is sorted or not (largest to smallest or smallest to largest).
I have defined my array in my function parameter, and I am trying to use a for loop to store the user's input, as long as it is above 0, in said array.
However, I am getting the error argument of type int is incompatible with parameter of type int*.
The exact error is the argument of type int is incompatible with parameter of type int*.
It is referring to line 22 and 23, these two;
isSorted(list[2000]); and
bool is = isSorted(list[2000]);.
I know this means my for loop is assigning a single value to my variable repeatedly from reading similar questions however I can not figure out how to fix this.
#include <iostream>
using namespace std;
bool isSorted(int list[]);
int main()
{
int i;
int list[2000];
int k = 0;
for (i = 0; i < 2000; i++)
{
int j;
while (j > 0)
{
cin >> j;
list[i] = j;
}
}
isSorted(list[2000]);
bool is = isSorted(list[2000]);
if (is == true)
cout << "sorted";
else
cout << "unsorted";
return 0;
}
bool isSorted(int list[])
{
int i = 0;
for (i = 0; i < 2000; i++)
{
if (list[i] > list[i + 1] || list[i] < list[i - 1])
{
return false;
}
else
return true;
}
}
I removed unused variable k.
Made 2000 parameterized (and set to 5 for testing).
In isSorted you are not allowed to return
true in the else as if your first element test would end in else you would return true immediately not testing other elements. But those later elements can be unsorted as well.
In isSorted you are not allowed to run the loop as for(i = 0; i < 2000; i++), because you add inside the for loop 1 to i and end up querying for i == 1999 list[2000], which is element number 2001 and not inside your array. This is correct instead: for (i = 0; i < 1999; i++). You also do not need to check into both directions.
You cannot call isSorted(list[2000]) as this would call is sorted with an int and not an int array as parameter.
You write int j without initializing it and then query while j > 0 before you cin << j. This is undefined behaviour, while most likely j will be zero, there is no guarantee. But most likely you never enter the while loop and never do cin
I renamed the isSorted as you just check in your example for ascending order. If you want to check for descending order you are welcome to train your programming skills and implementing this yourself.
Here is the code with the fixes:
#include <iostream>
using namespace std;
bool isSortedInAscendingOrder(int list[]);
const int size = 5; // Set this to 2000 again if you want
int main()
{
int i;
int list[size];
for (i = 0; i < size; i++)
{
int j = 0;
while(j <= 0)
{
cin >> j;
if(j <= 0)
cout << "rejected as equal or smaller zero" << endl;
}
list[i] = j;
}
if (isSortedInAscendingOrder(list))
cout << "sorted" << endl;
else
cout << "unsorted" << endl;
return 0;
}
bool isSortedInAscendingOrder(int list[])
{
for (int i = 0; i < size -1; i++)
{
if (list[i] > list[i + 1])
{
return false;
}
}
return true;
}
This is a definition of an array of 2000 integers.
int list[2000];
This is reading the 2000th entry in that array and undefined, because the highest legal index to access is 1999. Remember that the first legal index is 0.
list[2000]
So yes, from point of view of the compiler, the following only gives a single integer on top of being undefined behaviour (i.e. "evil").
isSorted(list[2000]);
You probably should change to this, in order to fix the immediate problem - and get quite close to what you probably want. It names the whole array as parameter. It will decay to a pointer to int (among other things loosing the information of size, but you hardcoded that inside the function; better change that by the way).
isSorted(list);
Delete the ignored first occurence (the one alone on a line), keep the second (the one assigning to a bool variable).
On the other hand, the logic of a your sorting check is flawed, it will often access outside the array, for indexes 0 and 1999. I.e. at the start and end of your loop. You need to loop over slightly less than the whole array and only use one of the two conditions.
I.e. do
for (i = 1; i < 2000; i++)
{
if (list[i] < list[i - 1])
/* ... */
The logic for checking ascending or descending sorting would have to be more complex. The question is not asking to fix that logic, so I stick with fixing the issues according to the original version (which did not mention two-way-sorting).
You actually did not ask about fixing the logic for that. But here is a hint:
Either use two loops, which you can break from as soon as you find a conflict, but do not return from the fuction immediatly.
Or use one loop and keep a flag of whether ascending or descending order has been broken. Then return true if either flag is still clear (or both, in case of all identical values) or return false if both are set.
I wanted to check whether what I wrote on the programming exam was working at least. And it turned out that it was not. And I do not understand why EXACTLY it does not work.
The task was to write a program with boolean function which should return true state if 2d matrix has only one row which consist entirely of negative element.
Here is the code:
#include "stdafx.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
bool cns();
const int n=5;
int a[n][n];
bool cns() {
int ts;
//!!!!
int lc; //!! I have initiated lc variable but still it does not work !!
//!!!
//standard 2d static quad matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << "a[" << i << "][" << j << "]=" << endl;
cin >> a[i][j];
}
}
//check whether the sum of elements of the row is negative or not
for (int i = 0; i < n; i++) {
ts = 0; //temp sum
for (int j = 0; j < n; j++) {
ts += a[i][j]; //I thought what if sum of elements is negative then the whole row is negative too
if (ts < 0) { //I have just realized that is wrong
lc++; //counter of negative lines, which consist entirely of negative elements
}
}
}
//only one row should be whole negative
if (lc == 1) {
return true;
}
else {
return false;
}
}
int main()
{
int lc;
cout << cns << endl;
return 0;
}
So could you tell me please where I did mistake with variable 'lc' and why compiler tells me "uninitialized local variable 'lc' used"?
You haven't initialized lc, but declared it.
To initialize a variable means giving it an initial value (which you should always do):
int lc = 0;
Initialising a variable is, essentially, giving it an initial value.
Your definition of lc
int lc;
does not initialise it. Since it is a variable of automatic storage duration (i.e. it is local to a block), it is not initialised.
Accessing its value therefore gives undefined behaviour.
The first thing that the code does with lc (within the first set of loops in your code) is
lc++;
Incrementing a variable of type int requires accessing its value, before producing an effect (doing the act of incrementing). Hence undefined behaviour.
The compiler warning is being issued because of that. To eliminate the warning, either initialise it where it is defined. For example;
int lc = 42;
or ensure the first operation is to set it to a valid value
int lc;
// later on the first thing ever done to lc is ...
lc = 47;
People often assume that all variables (of basic types, like int) which are defined without being explicitly initialised will have an initial value of 0 (zero). That is true in some other languages, but not in C++ - at least not in this context (an int of static storage duration IS zero-initialised).
Initialization is not what you have done here. As stated by amc176 you have only declared it.
When you declare variable lc, memory is reserved on the stack. The amount of memory reserved depends on the data type (a char will take up more memory than an int).
However, if you do not provide an initial value for that variable (i.e. initialize it) the initial value of the data type will be exactly what was present in that specific piece of memory. That is why your compiler is complaining.
I am in a discrete mathematics class and one of the hw problems is to implement a bubble sort. Here's my futile attempt because it does not output the solution. Please advice. Thank you.
#include <iostream>
#include <cstdlib>
using namespace std;
void BubbleSort();
int array1[100] = {0};
int k;
int main()
{
cout << "Enter your numbers and when you are done, enter 0000:\n";
int x = 0;
int i;
while (i != 0000)
{
cin >> i;
array1[x] = i;
x++;
k = x;
}
BubbleSort();
system("pause");
return 0;
}
void BubbleSort(){
int temp;
for( int i = 0; i < k; i++ ){
if ( array1[i] > array1[i+1]){
temp = array1[i+1];
array1[i+1] = array1[i];
array1[i] = temp;
}
}
int x = 0;
while (x <= k)
{
cout << array1[x] << "\n";
x++;
}
}
Please only use basic programming techniques because this is my first programming class. Thank you.
Edit: fixed the relational operator. But now I get incorrect results.
while (x >! k)
This doesn't do what you think it does. If you want something that says "while x is not greater than k", you want <=. Since array1[k] isn't one of the elements you sorted, though, you probably want <.
while (x < k)
Note that for exists for loops like these:
for (int x = 0; x < k; x++) {
cout << array1[x] << "\n";
}
As for the new bug, you're only doing one round of bubbling in your bubble sort. You need another for loop. Also, i is never initialized in main, and i != 0000 isn't going to check whether the user literally entered 4 zeros. It'll only check whether the user's input was equal to the number 0.
The primary problem is here:
while (x >! k)
On the first iteration, the condition checks whether (0 > !k), and k is not 0, so !k is 0, so the condition is false and the loop never executes. Try using:
for (int x = 0; x < k; x++)
cout << array1[x] << "\n";
You also have a problem in the sort phase of your bubble sort; you only iterate through the data once, which is not enough to sort it, in general.
Finally, some design issues.
You should have one function to sort the data and a separate function to print it. Don't combine the two functions as you have done here.
Avoid global variables. Pass the array and its operational length to the sort function, and to the print function if you have one.
The two general approaches for Fibonacci series generation are:
The traditional approach, i.e., running through a for loop inside a function.
Recursion
I came across another solution
#include <iostream>
using namespace std;
void fibo() {
static int y = 0;
static int x = 1;
cout << y << endl;
y = x + y;
x = y - x;
}
int main() {
for (int i = 1; i <= 1; i++) {
fibo();
}
return 0;
}
This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?
I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?
Disadvantages I can immediately see:
By essentially making the state global, it's not thread-safe
You can only ever run through the sequence once, as there's no way to reset
I would favour an approach which keeps the state within an object which you can ask for the next value of - an iterator, basically. (I've never been certain how easily the Fibonacci sequence maps to C++ iterators; it works fine with C# and Java IEnumerable<T> and Iterable<T> though.)
The solution you found is decent for when you need to store the state (for example, when you calculate a Fibonacci number, do something based on it, and then calculate another), but using this from two places in your code will likely give funny results. This is because the static variables will always be the same, no matter from where you call it. I would instead suggest:
class FiboNumbers {
public:
FiboNumbers() :
x_(1), y_() {}
int getNext() {
x_ += y_;
y_ = x_ - y_;
return x_;
}
private:
int x_, y_;
};
This offers the same keeping-of-state, but allows you to create multiple instances of the class, therefore allowing you to have different parts of the code that calculate their own Fibonacci series.
Minor note: the code I posted will produce the same series as the example you posted, but it will produce the real Fibonacci sequence, which starts with 0 1 1 2...
I am a C++ student (1.5 months into it).
Give feedback to this different way I have thought of for Fibonacci series.
#include<iostream>
using namespace std;
void fibseries(long int n)
{
double x=0;double y=1;
for (long int i=1;i<=n;i++)
{
if(i%2==1)
{
cout<<x<<" ";
x=x+y;
}
else
{
cout<<y<<" ";
y=x+y;
}
}
}
main()
{
long int n=0;
cout<<"The number of terms ";
cin>>n;
fibseries(n);
return 0;
}
I'm not sure what this function is really supposed to do. It
only works in the exact loop you present, and as others have
pointed out, it only works once. (And there's probably a typo
in your loop, since your complete program outputs "0", and
nothing else.) What advantage does it offer over:
int y = 0;
int x = 1;
for ( int i = 0; i < count; ++ i ) {
std::cout << y <<std::endl;
y = x + y;
x = y - x;
}
? It's more complex, far less robust, and far less useful.
As was said before, the advantage of the static variables is, in principle, that it's cheaper to calculate the n -th Element of a sequence where the n - 1 -th has already been evaluated.
The big drawback, apart from the problems inherent to static variables, is that you don't have any way to get back to an earlier point in the sequence, nor do you really have a good control over where in the sequence you are at a given time.
Using a class, as recommended by Sevis, is certainly the better way of implementing such a static-like approach: this makes everything safer, gives you an easy way to get back to the sequence start (by simply reinitializing the object) and also makes it possible to implement further functionality, like going back k steps, looking up the present position, etc..
I think this pointer approach would be more useful for you.
void main()
{
int i,p, *no,factorial,summ;
int fib(int p);
clrscr();
printf("\n Enter The Number:");
scanf("%d", no);
printf("\n The Fibonnacci series: \n");
for(i=0; i < *no; i++)
printf("%d\n", fib(i));
getch();
}
int fib(int p)
{
if(p == 0)
return(0);
if(p >= 1 && p <= 2)
return(1);
else
return(fib(p - 1) + fib(p - 2));
}
I have following code to accomplish prefix sum task:
#include <iostream>
#include<math.h>
using namespace std;
int Log(int n){
int count=1;
while (n!=0){
n>>=1;
count++;
}
return count;
}
int main(){
int x[16]={39,21,20,50,13,18,2,33,49,39,47,15,30,47,24,1};
int n=sizeof(x)/sizeof(int );
for (int i=0;i<=(Log(n)-1);i++){
for (int j=0;j<=n-1;j++){
if (j>=(std::powf(2,i))){
int t=powf(2,i);
x[j]=x[j]+x[j-t];
}
}
}
for (int i=0;i<n;i++)
cout<<x[i]<< " ";
return 0;
}
From this wikipedia page
but i have got wrong result what is wrong? please help
I’m not sure what your code is supposed to do but implementing a prefix sum is actually pretty easy. For example, this calculates the (exclusive) prefix sum of an iterator range using an arbitrary operation:
template <typename It, typename F, typename T>
inline void prescan(It front, It back, F op, T const& id) {
if (front == back) return;
typename iterator_traits<It>::value_type accu = *front;
*front++ = id;
for (; front != back; ++front) {
swap(*front, accu);
accu = op(accu, *front);
}
}
This follows the interface style of the C++ standard library algorithms.
To use it from your code, you could write the following:
prescan(x, x + n, std::plus<int>());
Are you trying to implement a parallel prefix sum? This only makes sense when you actually parallelize your code. As it stands, your code is executed sequentially and doesn’t gain anything from the more complex divide and conquer logic that you seem to employ.
Furthermore, there are indeed errors in your code. The most important one:
for(int i=0;i<=(Log(n)-1);i++)
Here, you’re iterating until floor(log(n)) - 1. But the pseudo-code states that you in fact need to iterate until ceil(log(n)) - 1.
Furthermore, consider this:
for (int j=0;j<=n-1;j++)
This isn’t very usual. Normally, you’d write such code as follows:
for (int j = 0; j < n; ++j)
Notice that I used < instead of <= and adjusted the bounds from j - 1 to j. The same would hold for the outer loop, so you’d get:
for (int i = 0; i < std::log(n); ++i)
Finally, instead of std::powf, you can use the fact that pow(2, x) is the same as 1 << x (i.e. taking advantage of the fact that operations base 2 are efficiently implemented as bit operations). This means that you can simply write:
if (j >= 1 << i)
x[j] += x[j - (1 << i)];
I think that std::partial_sum does what you want
http://www.sgi.com/tech/stl/partial_sum.html
The quickest way to get your algorithm working: Drop the outer for(i...) loop, instead setting i to 0, and use only the inner for (j...) loop.
int main(){
...
int i=0;
for (int j=0;j<=n-1;j++){
if (j>=(powf(2,i))){
int t=powf(2,i);
x[j]=x[j]+x[j-t];
}
}
...
}
Or equivalently:
for (int j=0; j<=n-1; j++) {
if (j>=1)
x[j] = x[j] + x[j-1];
}
...which is the intuitive way to do a prefix sum, and also probably the fastest non-parallel algorithm.
Wikipedia's algorithm is designed to be run in parallel, such that all of the additions are completely independent of each other. It reads all the values in, adds to them, then writes them back into the array, all in parallel. In your version, when you execute x[j]=x[j]+x[j-t], you're using the x[j-t] that you just added to, t iterations ago.
If you really want to reproduce Wikipedia's algorithm, here's one way, but be warned it will be much slower than the intuitive way above, unless you are using a parallelizing compiler and a computer with a whole bunch of processors.
int main() {
int x[16]={39,21,20,50,13,18,2,33,49,39,47,15,30,47,24,1};
int y[16];
int n=sizeof(x)/sizeof(int);
for (int i=0;i<=(Log(n)-1);i++){
for (int j=0;j<=n-1;j++){
y[j] = x[j];
if (j>=(powf(2,i))){
int t=powf(2,i);
y[j] += x[j-t];
}
}
for (int j=0;j<=n-1;j++){
x[j] = y[j];
}
}
for (int i=0;i<n;i++)
cout<<x[i]<< " ";
cout<<endl;
}
Side notes: You can use 1<<i instead of powf(2,i), for speed. And as ergosys mentioned, your Log() function needs work; the values it returns are too high, which won't affect the partial sum's result in this case, but will make it take longer.