Skip to content

Instantly share code, notes, and snippets.

@khzaw
Created March 12, 2015 12:07
Show Gist options
  • Save khzaw/cfd495cbea50b15af820 to your computer and use it in GitHub Desktop.
Save khzaw/cfd495cbea50b15af820 to your computer and use it in GitHub Desktop.
int count_x(char* p, char x) {
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
if(p == nullptr) return 0;
int count = 0;
for(; p != nullptr; ++p)
if(*p == x)
++count;
return count;
}
int count_x(char* p, char x) {
int count = 0;
while(p) {
if (*p == x)
++count;
++p;
}
return count;
}
bool accept2() {
cout << "Do you want to proceed (y or n) ? \n";
char answer = 0;
cin >> answer;
switch(answer) {
case 'y': return true;
case 'n': return false;
default:
}
}
struct Vector {
int sz; // number of elements
double* elem; // pointer to elements
}
Vector v;
void vector_init(Vector& v, int s) {
v.elem = new double[s]; // allocate an array of s doubles
v.sz = s;
}
double read_and_sum(int s) {
Vector v;
vector_init(v, s);
for(int i = 0; i != s; ++i) {
cin >> v.elem[i];
}
double sum = 0;
for(int i = 0; i != s; ++i)
sum += v.elem[i];
return sum;
}
/*
* unary suffix * = pointer to
* unary suffix & = reference to
*
* unary prefix * = contents of
* unary prefix & = address of
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment