Counter returns unexpected value - counter

This my cpp code and I am confused because cnt returns x = 0 !
#include <iostream>
using namespace std;
int i;
int cnt () {
for (i = 0; i<15; i++) {
return i;
}
}
int main () {
int x;
x = cnt();
cout << x << endl;
}```

The return function stops every other instruction in the function from being executed and returns the chosen value to the function which called it. Your loop is executed just once.

Related

C++ Fix the following code so that it will correctly recursively traverse a directory tree in order to find where a particular file is

I have an assignment as following: Write a program will ask the user how many random numbers to generate. Then it will present a menu which has the options of Display, Average, Median, and Standard Deviation, Regenerate, and Quit. Without the use of a switch statement, or an if statements, or pointers to functions, have the program execute the user's selection from the menu. (Note: Function pointers are not allowed!)
This is what I have so far:
#include <iostream>
#include <cstdlib>
#include <array>
#include <cmath>
#include <stdlib.h>
#include <map>
using namespace std;
template <typename T> class wrapperclass
{
public:
static T myclass;
};
class Display
{
public:
static void myFunction(int random[], int num)
{
for(int i=0; i<num; ++i)
{
cout << random[i] <<endl;
}
}
};
class Average
{
public:
static double myFunction(int random[], int num)
{
double avg = 0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
return avg/num;
}
};
class Median
{
public:
static double myFunction(int random[], int num)
{
double mid = 0;
if(num % 2 == 0)
{
mid = (random[num/2] + random[num/2-1])/2;
}
else
{
mid = random[num/2];
}
return mid;
}
};
class StdDi
{
public:
static double myFunction(int random[], int num)
{
double avg=0;
double total=0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
avg = avg/num;
for(int i=0; i<num; ++i)
{
total += (avg-random[i])*(avg-random[i]);
}
total = total/num;
return sqrt(total);
}
};
class renerate
{
public:
static void myFunction(int)
{
}
};
class quit
{
public:
static void myFunction()
{
exit(EXIT_FAILURE);
}
};
int main()
{
int num = 0;
int option = 0;
map<int, class T> magic;
cout << "How many random numbers would u like to generate? " << endl;
cin >> num;
int random[num];
for(int i=0; i<num; ++i)
{
random[i] = rand() % 100 + 1;
}
cout << " Menu"<<endl
<< "1. Display"<<endl
<< "2. Average"<<endl
<< "3. Median"<<endl
<< "4. Standard Deviation"<<endl
<< "5. Renerate"<<endl
<< "6. Quit"<<endl;
cin >> option;
cout<<wrapperclass<Average>::myclass.myFunction(random, num);
return 0;
}
I'm about to directly pass the user input "option" into that "wrapperclass" like this "wrapperclass" so I can simply call the .myFunction since all classes have the same function name. but this won't work for c++ so is there any work around?

getchar(), putchar(char), EOF

#include<stdio.h>
int main(){
int c = getchar();
while(c != EOF){
putchar(c);
c = getchar();
}
}
In above code why does not the program terminates by itself after c becomes EOF?
Reference of the code > Book: K&R's The C Programming Language 2nd Edition,
Page: 18
getchar() will return EOF only if the end of file is reached. The ‘file’ here is the standard input itself.
This can be written as:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
{
/*getchar() returns the the next available value which is in the input
buffer*/
putchar(c);
}
}

std::sort using member function in the same class?

I have a class "PclProc" and I want to use std::sort.
I write a compare function in the same class because this comparing need the "in_ptr" which is a variable in the same class.
But as I did as following, there is always an error:
error: no matching function for call to
‘sort(std::vector::iterator, std::vector::iterator,
)’
std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);
bool PclProc::MyCompare(int id1, int id2)
{
return in_ptr->points[id1].z<in_ptr->points[id2].z;
}
float PclProc::MedianZDist(pcl::PointIndices cloud_indice)
{
std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);
int size=cloud_indice.indices.size();
float median_x,median_y;
...
Example of a functor being used for std::sort. vector D is the data, vector I is the indices to D. I is sorted according to D with std::sort using the functor. std::sort only creates one instance of class lessthan, then uses that one instance for all of the compares.
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>
typedef unsigned int uint32_t;
#define SIZE 16
class example{
public:
std::vector<uint32_t> D; // data
std::vector<uint32_t> I; // indices
example(void)
{
D.resize(SIZE);
I.resize(SIZE);
for(uint32_t i = 0; i < SIZE; i++){
D[i] = rand()%100;
I[i] = i;
}
}
void displaydata(void)
{
for(size_t i = 0; i < SIZE; i++)
std::cout << std::setw(3) << D[I[i]];
std::cout << std::endl;
}
class lessthan // lessthan functor for std::sort
{
public:
const example &x;
lessthan(const example &e ) : x(e) { }
bool operator()(const uint32_t & i0, const uint32_t & i1)
{
return x.D[i0] < x.D[i1];
}
};
void sortindices(void)
{
std::sort(I.begin(), I.end(), lessthan(*this));
}
};
int main()
{
example x;
x.displaydata();
x.sortindices();
x.displaydata();
return 0;
}

Passing array to stringstream

This is something I had never noticed but for some reason you can't do something like
sstr << myarray;
If you do that "sstr" would contain the address of "myarray",You would have to do
for(int i;i < sizeof(myarray);i++)
{
sstr << myarray[i];
}
I would like to know why does this happens, I don't remember ever having to do that, but personally I think sometimes reality itself changes just to annoy me.
You need to define your own stream operation for an array to be able to display it.
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class mydata
{
public:
mydata(int size = 0) { for (int i = 0; i < size; i++) add(0); }
~mydata() { }
void add(T x) { data.push_back(x); }
void remove(int pos) { data.erase(data.begin() - pos); }
T& operator[](int pos) { return data[pos]; }
friend ostream& operator<<(ostream& os, const mydata<T>& name) {
for (int i = 0; i < x.data.size(); i++) os << x.data[i] << " "; return os; }
private:
vector<T> data;
};
That would be a standard class for encapsulating your data. If you wanted to do an operation like mydata<int> b(8); b[7] = 8; you can. The reason the code for the << operator is inside the class is because templates requires typename specific code to be inside the template itself.
Finally, this is how this code can be implemented.
int main()
{
mydata<char> charData;
mydata<int> intData;
for (int i = 0; i < 20; i++) {
charData.add(65+i);
intData.add(i);
}
cout << charData << endl;
cout << intData;
cin.get();
return 0;
}
The output looks like this:
A B C D E F G H I J K L M N O P Q R S T
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Mex file gives segmentation fault only on second use

The following code compiles successfully and returns the correct results when called the first time. Making the same call a second time, I get a segmentation fault error.
//% function TF = InWindow(Date,WindowStartDates,WindowEndDates,EndHint)
//% INWINDOW returns true for window that contains Date. All inputs must be
//% uint32 and WindowEndDates must be sorted.
//% EndHint is an optional input that specifies the row number to start
//% searching from.
#include "mex.h"
#include "matrix.h"
#include "math.h"
void CalculationRoutine(mxLogical *ismember, uint32_T *Date, uint32_T *WindowStartDates, uint32_T *WindowEndDates, unsigned int *StartIndex, int NumObs) {
mwIndex Counter;
// Find the first window that ends on or after the date.
for (Counter = (mwIndex) *StartIndex; Counter < NumObs; Counter++) {
if (*Date <= *(WindowEndDates+Counter)) {
break;
}
}
*StartIndex = (unsigned int) Counter;
// Now flag every observation within the window. Remember that WindowStartDates
// is not necessarily sorted (but WindowEndDates is).
for (Counter = (mwIndex) *StartIndex; Counter < NumObs; Counter++) {
if (*Date >= *(WindowStartDates+Counter)) {
*(ismember+Counter) = true;
}
}
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
mxArray *ismember;
unsigned int *StartIndex;
//Input Checking.
if (nrhs == 3) {
// Default Hint to first entry.
mexPrintf("SI Starts OK.\n");
*StartIndex = 1;
mexPrintf("SI Ends OK.\n");
} else if (nrhs == 4) {
if (!mxIsUint32(prhs[3])) {
mexErrMsgTxt("EndHint must be uint32.");
}
StartIndex = mxGetData(prhs[3]);
} else {
mexErrMsgTxt("Must provide three or four input arguments.");
}
// Convert the hint to base-zero indexing.
*StartIndex = *StartIndex - 1;
// Check the inputs for the window range.
if (!mxIsUint32(prhs[0])) {
mexErrMsgTxt("DatesList must be uint32.");
}
if (!mxIsUint32(prhs[1])) {
mexErrMsgTxt("WindowStartsDates must be uint32.");
}
if (!mxIsUint32(prhs[2])) {
mexErrMsgTxt("WindowEndsDates must be uint32.");
}
if (mxGetM(prhs[1]) != mxGetM(prhs[2])) {
mexErrMsgTxt("WindowStartDates must be the same length as WindowEndDates.");
}
// Prepare the output array.
ismember = mxCreateLogicalArray(mxGetNumberOfDimensions(prhs[1]), mxGetDimensions(prhs[1]));
CalculationRoutine(mxGetLogicals(ismember),mxGetData(prhs[0]),
mxGetData(prhs[1]), mxGetData(prhs[2]), StartIndex, (int) mxGetM(prhs[1]));
plhs[0] = ismember;
}
I call it with:
>>InWindow(uint32(5),uint32((1:6)'),uint32((3:8)'))
The code reaches the line between the two mexPrintf calls before the segmentation fault (ie the first call prints, but not the second).
I am on Matlab 2007a (yes, I know), Win7 64bit and VS 2008.
You need to initialize the pointer StartIndex - you're "lucky" that it works the first time, since it is not pointing to a defined memory location. Why not do something more like:
unsigned int StartIndex;
// and either:
StartIndex = 1;
// or:
StartIndex = * (static_cast< unsigned int * >( mxGetData(prhs[3]) ) );