C and C++ Distributed by justEtc |
Just went through the book "The C Programming Language" by Kernighan and Ritchie. I read the book several times in the past. Just reviewed it again.
Introduction to CProgramming Languageby Mr. S. Ahmed
Topics/Concepts
Structure of a C Program
How does a C program look like? #includemain() { printf("hello, world\n"); }
The ‘Hello World’ Program
Program Execution, Program in Action
Remember
Some Variations of the Printf() Function
Concepts to Understand
Concepts to Understand
Note:
Variable and Expressions
Control Flow. What is it?
Control Flow
if (expression) statement1 else statement2 ---- if (expression) statement1 else if (expression) statement2 else statement3
If then Else
if (a > b) z = a; else z = b; ---- if (a > b) z = a; else if (b>a) z = b; else if (a==b) x=y; else printf(“nothing”);
Switch-Case
If (1==a) statement1 else if (2==a) Statement2 else if (3==a) Statement3 else statement4
Switch-Case Equivalent of If
switch(a){
Case 1:statement1;break;
Case 2:statement2;break;
Case 3:statement3;break;
default:statement4;break;
}
Switch
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}
Loop
Loops Syntax
while (expression){
Statement
}
for (expr1; expr2; expr3){
Statement
}
expr1;
while (expr2) {
statement
expr3;
}
Loops Example
int n=100,i=0;
for (i = 0; i < n; i++){
printf(”%d\n”,i);
}
int n=100,i=0; while(i
Loop Example
int n=100,i=0;
do {
printf(”%d\n”,i);
i++;
} while(i
Go to Statement
Syntax Go to Label …… ……… Label: …….
Pointers
Pointers
Pointers
Pointers
Pointers as Function Parameters
Call by reference applies here
void swap(int *px, int *py)
/* interchange *px and *py */
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
main()
{
swap(x, y);
//The values of x and y will also get changed here
}
Pointers and Arrays
Pointers and Multi-dimensional
Arrays:Example
int a[10][20];
int *a[10];
char name[][50] = { "Illegal month", "Jan", "Feb", "Mar" };
char *name[] = { "Illegal month", "Jan", "Feb", "Mar" };
Bitwise Operators
Left and Right Shifts
I/O Functions
File Operations
Common I/O Functions
Structures
Defining Structures
struct student {
int id;
char *name;
char * address;
char *cell;
};
Defining Structures
We can declare and assign at the same time
Structures
Pointers to Structures
Array of Structures
struct student{
int id;
char *name;
char *address;
char *cell;
} studentList = {
{100,”name1”,”address1”},
{101,”name2”,”address2”},
{102,”name3”,”address3”}
};
Union
Union
union tag {
int ival;
float fval;
char *sval;
} u;
Enum
enum DAY {
saturday,
sunday ,
monday,
tuesday,
wednesday,
thursday,
friday
} workday;
enum DAY today = wednesday;
I/O Functions
I/O Functions: Mathematical Functions
Reference: "The C Programming Language”: Kernighan and Ritchie
Here, I am listing two presentation slides on C and C++. Yes, I myself have created them. I am planning to improve the slides shortly and create training videos on them (esp. c++ - it needs much work). Have fun.
This short note is for those who already know C++ and want to refresh their memory. Beginners can still take a look to get an overall idea.
Sorry, this will make sense only if you want to refresh your memory on C++ syntax. cout << "Enter two integers:" << endl; // output to screen cin >> n >> m; // Note: Using endl prints out a newline and flushes the output buffer. cout << "number of digits in char: " << numeric_limits::digits << '\n'; if (n > m) { // if n is bigger than m, swap them int temp = n; // declare temp and initialize it n = m; // assign value of m to n m = temp; // assign value of temp to m } long iii = i; // implicit conversion from int to long iii = long(i); // explicit conversion from int to long for (double d = 1.1; d <= 9.9; d += 0.2) sum += sin(d); using namespace std; #include int main() { using namespace std; } const int mxdigits = 999500; int* p = &n; int m = 200; *p = m; double* tryd = new double (x); unsigned int jj = ii; cout.width(2); cout << i; struct point2d { char nm; float x; float y; }; point2d pt2 = { 'A', 3.14, -38 }; union val { int i; double d; char c; }; double* tmv = new double[n]; int n = atoi(argv[1]); // first integer is assigned to n int* local = new int; *local = 555; namespace Vec { const int maxsize = 100000; // a const number double onenorm(double*, int); // L 1 norm } double Vec::onenorm(double* v, int size) { } std::cout <<"Approx root near 7.7 by newton method is: " << root << '\n'; --- std::srand(time(0)); // seed the random number generator for (int i = 0; i< n; i++) dp[i] = std::rand()%1000; std::sort(dp, dp+n); --- double d = - 12345.678987654321; cout.setf(ios_base::scientific, ios_base::floatfield); // scientific format cout.setf(ios_base::uppercase); cout.width(25); cout.precision(15); cout.setf(ios_base::left, ios_base::adjustfield); // adjust to left cout << d << "\n"; -------- double sum(int num, ...); va_list argPtr; va_start(argPtr, num); // initialize argPrt. num is the last known argument double sum = 0; for( ; num; num--) { sum += va_arg(argPtr, double); // argument of type double is returned } va_end(argPtr); // deallocate stack pointed to by argPtr return sum; -- struct point2d { double x; double y; friend double norm(point2d p) { // a friend return sqrt(p.x*p.x + p.y*p.y); // distance to origin } }; ---- class triangle { point2d* vertices; public: triangle(point2d, point2d, point2d); // constructor ~triangle() { } // destructor double area() const; // a function member }; ---- class triple { // a triple of numbers float* data; public: triple(float a, float b, float c); // constructor ~triple() { } // destructor, also defined here friend triple add(const triple&, const triple&); // add is a friend }; inline triple::triple(const triple& t) { data = new float [3]; for (int i = 0; i < 3; i++) data[i] = t.data[i]; } ----- operator overloading class Cmpx { // class for complex numbers private: double re; // real part of a complex number double im; // imaginal part of a complex number public: Cmpx(double x = 0, double y = 0) { re =x; im =y; } // constructor Cmpx& operator+=(Cmpx); // operator +=, eg z1 += z2 Cmpx& operator-=(Cmpx); // operator -=, eg z1 -= z2 Cmpx& operator++(); // prefix, z1 = ++z Cmpx operator++(int); // postfix, z1 = z++ friend Cmpx operator*(Cmpx, Cmpx); // binary *, z = z1 * z2 friend std::ostream& operator<<(std::ostream&, Cmpx); // operator << friend std::istream& operator>>(std::istream&, Cmpx&); // operator >> }; ---------------- template class Vcr { int lenth; // number of entries in vector T* vr; // entries of the vector public: Vcr(int, T*); // constructor Vcr(const Vcr&); // copy constructor ~Vcr(){ delete[] vr; } // destructor }; // partial specialization template class Vcr< complex > { int lenth; // number of entries in vector complex * vr; // entries of the vector public: Vcr(int, complex *); // constructor Vcr(const Vcr&); // copy constructor ~Vcr(){ delete[] vr; } // destructor }; // complete specialization template<> class Vcr< complex > { int lenth; // number of entries in vector complex * vr; // entries of the vector public: Vcr(int, complex *); // constructor Vcr(const Vcr&); // copy constructor ~Vcr(){ delete[] vr; } // destructor }; ---------- complex aa = complex (3, 5); --- list nodes; // a list of integers for nodes nodes.push_front(10); // add 10 at the beginning nodes.push_back(5); // add 5 at the end nodes.pop_back(); // remove last element nodes.remove(10); // remove element 10 for (list ::iterator j = nodes.begin(); j != nodes.end(); j++) cout << *j << " "; // *j is the element at position j nodes.sort(); nodes.unique(); nodes.reverse(); nodes.insert(i, 2); // insert before element that i refers to nodes.insert(i, 5, 7); // insert 5 copies of 7 nodes.erase(i); ft.merge(sd); // ft has the merged list, sd will be empty list ::iterator ii = find(ft.begin(), ft.end(), 5.5); sd.splice(sd.begin(), ft, ii); ---- VECTOR std::vector vi(10); for (int i = 0; i < 10; i++) vi[i] = (i-5)*i; std::sort(vi.begin(),vi.end()); std::unique(vi.begin(),vi.end()); -----
Not really for the beginners. If you had experience working with C++ in the past, then taking a look at this short-note will help to recover your knowledge in C++.
Multiple inheritance means that one subclass can have more than one superclass. This enables the subclass to inherit properties of more than one superclass and to ``merge'' their properties.
char *strp; /* strp is `pointer to char' */
*strp = 'a'; /* A single character */
A pointer to characters can be used to point to a sequence of characters
Class Structure:
class Foo {
// private as default ...
public:
// what follows is public until ...
private:
// ... here, where we switch back to private ...
public:
// ... and back to public.
};
Struct:
class Struct {
public: // Structure elements are public by default
// elements, methods
};
Method definition - outside of the class
void Point::setX(const int val) {
_x = val;
}
void Point::setY(const int val) {
_y = val;
}
Access a method:
apoint.setX(1); // Initialization
Inheritance:
class Point3D : public Point {}
C++ has two types of inheritance: public and private. By default, classes are privately derived from each other
You can inherit as private, protected, public. Private members always come as private in the subclass. Public members of the super class come to the subclass according/(as) to the inheritance type
Multiple Inheritance:
class DrawableString : public Point, public DrawableObject {}
Virtual Function in C++
You can use the keyword 'virtual' before a function declaration to make the function virtual. Subclasses to these class can define the function as they want. It still remains virtual in the subclasses.
http://www.codersource.net/published/view/325/virtual_functions_in.aspx
-- will update and add later
Reference: http://gd.tuwien.ac.at/languages/c/c++oop-pmueller/tutorial.html
It's better that you clearly understand these
According to: http://yosefk.com/c++fqa/templates.html#fqa-35.10, C++ Templates are slow.
Though theoretically, templates can be as efficient as straightforward code or more efficient than straightforward code. However, commercial compilers don't optimize templates code in that level. So practically templates are slower. Also, some other complexities may arise while using templates.
FAQs about templates http://yosefk.com/c++fqa/templates.html
Transform binary representation into integral number using bitset
Call member function for each element in vector
Print minimum, maximum, and sum of the valarray
valarray with double value inside
Use sorting criterion in sort function
Here, I am listing two presentation slides on C and C++. Yes, I myself have created them. I am planning to improve the slides shortly and create training videos on them (esp. c++ - it needs much work). Have fun.