You are on page 1of 19

/*C++ BASICS NOTE: the printf statement from 'C' has been used in some places however the

cout<< statement is what should be used in C /*OPERATORS & DATA TYPES ARITHMETIC OPERATORS (in order of precedence!!)*/ ++ -/* increment & decrement (unary) operators that increase or decrease the value of a variable by 1 everytime*/ int i=5; i++; /*instead of*/ i=i+1;/*i must be an lvalue to store the increment/decrement result, i++ isnt i++;expression executes b4 variable is changed in memory, ++i;the variable is changed b4 expres. exec int a,b=2,c=5;a=++b;printf("%d%d%d",a,++c,b);/*prints3,6,3*/a=b++;printf("%d%d%d",a,c++,b);/*prints2,5,3*/ () * / % + // brackets, multiply, divide, remainder(returns the remainder after a division), plus, minus << >> /* e.g */ a<<b /* shift a by b bits to the left EQUALITY & RELATIONAL OPERATORS (in continued order of precedence from above!!) Can be used in program flow statements but when used on there own, the compiler returns a value of 1 for true and 0 for f < <= > >= // less than, less than or equal to, etc == != // equal to, not equal to && || // and, or (inclusive) (a||b)&&!(a&&b); // this is how to obtain the exclusive or (xOR) & | ^ /* bitwise and, bitwise or, bitwise xOR (i.e compare the bits; binary equivalent) NEGATION*/ !expression

/*

ASSIGNMENT OPERATORS (in continued order of precedence from above!!)*/ = += -= *= /= %= // equals, the others are used like so: int c=5; c*=c; /*instead of*/ c=c*c //i.e c=25 <<= >>= &= |= ^= /* used in similar manner as above CONDITIONAL OPERATOR It is similar to an if/else statement but can be used within "cout" statments */ expression ? do this if true : else do this /*e.g*/c=5>3?a:b;//sets the value of a to c, since 5 is greater than 3 /*e.g*/cout<<(grade>20?"y":"n");/*prints y if grade is greater than 20 else n Note: When dealing with bitwise operators, 1st convert the decimal no's to binary ESCAPE OPERATORS*/ \n

/* moves the cursor to a new line, should be used within quotes can be used to continue a part of the same function on a new line, instead of using the same

\t \a \\ \"

// // // // /*

function twice on each line like so: line1 printf("hello"); line2 printf("world"); etc which would be written instead as: printf("hello\nworld\nthis is\nmy 1st program\n"); */ tab --> alert, sounds the system bell print the backslash character print the double quote character see notes for more!!

DATA TYPES*/ char // short int // int // long int // bool // float // double // long double // void // wchar_t // string

8-bit(1 byte) character or small integer; 'signed' or 'unsigned'. 16-bit(2 bytes) integer; can use just 'short', 'signed' or 'unsigned'. 32-bit(4 bytes) integer; 'signed' or 'unsigned'. 32-bit integer; can use just 'long', 'signed' or 'unsigned'. 8-bit boolean number; takes only 2 values, 'true' becomes 1 or 'false' becomes 0 32-bit floating point number 64-bit(8 bytes) double precision floating point number 64-bit(8 bytes) long double precision floating point number void is valueless 16-bit wide character; takes 1 wide character

/* must include the library */#include<string.h>/*e.g*/string mystring="kings college";/* it works in the same way as a single row character array (string) except that it does not end with the null'\0' character and it accepts "spaces" between words even when "cin" is used to initialize it.

AMERICAN STANDARD CODE FOR INFORMATION EXCHANGE (ASCII) SEE NOTES FOR ASCII TABLE & EXTENDED ASCII Uses:*/ char letter='\130' /*instead of*/ char letter='X' char ch1='1', ch2='3' printf("%c", ch1+ch2);/*'1'=49 & '3'=51 in ascii, it prints d(51+49=100=d) SOME USEFUL KEYWORDS/CHARACTERS*/ EOF /* End of file character e.g*/while(grade=cin.get()!=EOF){do something}/* expects user to input characters, assigns it to grade and does something until user presses ctrl and z (which returns the end of file character). note: with this particular use in the while statement (above), when "enter" is pressed, cin.get() accepts this as a chara assigns grade=10. Unless this result is required it must be handled by the program at some point maybe using a switch sta static /* The static keyword can be used to declare variables, functions, class data members and class functions. The static keyword can be used in the following situations;

When you declare a static global variable or function, the compiler initializes it to 0 unless you specify anot When you declare a static variable in a function, the variable retains the same value whenever the function is it the value it was in the function b4 the function was exited is retained, so the next time the function is c will have that value and continue from there. When you declare a static data member in a class; one copy of the member is shared by all instances of the clas An integral data member that you declare as const static can have an initializer. When you declare a static member function in a class declaration, the static keyword specifies that the functio shared by all instances of the class. A static member function cannot access an instance member because the fu does not have an implicit this pointer. To access an instance member, declare the function with a parameter th an instance pointer or reference.

VARIABLES lvalue expression(left value): one which evaluates to a value whom is allocated a location in memory to store it. e.g a,++a rvalue expression(right value): is the opposite e.g 4+2*a. note: an lvalue is always an rvalue but the converse is not true. DEFINING/DECLARING ALL variables must be defined before values can be assigned to them & used in calculations.*/ int x,y,sum; char ch; float r; /* this defines the variables x,y & sum(integers), ch(character), r(floating point no.) INITIALIZING You can use the cin>> function as shown later to ask the user to input a value to be assigned to the variable OR you can define & intitalize together OR you can assign a value during the program:*/ int x=1, y(2); string z("AB"); float sum=x+y; // x,y,z & sum have been defined & initialized at the same time int x=1==1, y=2==1; // assigns x as 1 (true) and y as 0(false) int x, y=2+(x=2); // sets x=2 and sets y = 2+x = 4 int x, y=(x=2,x+2); // does exactly the same as above int a=b=c=5; // sets a=5,b=5,c=5 int x, float y=3.14; x=int(y); // sets x=3 and y=3.14; can also write x=(int)y this is called typecasting int x=3, &y=x; // y is declared as a reference to x i.e if y is altered, x is altered & vice versa// similar to how pointers work BUT &y must be initialized emmediately!! /* note: memory space is not allocated for &y! it simply acts as a nickname for x. PASSING VARIABLES int x,y; myFunction(x,y) myFunction(&x,y) myFunction(&x,&y) TO FUNCTIONS */ // x and y are passed by value to a function with prototype; int myfunction(int x, int y); // passes x by reference and y by value to ; int myfunction(int *x, int y); // x and y are passed by reference to; int myfunction(int *x, int *y);

myFunction(x,y)

/* x and y are passed by reference if the prototype is like so; int myFunction(int &x,&y); (recall it is not necessary to put the variable names i.e x,y within the prototype declaration) note the 1st one desribes passing variables to functions designed to accept variables and the 2nd describes passing variables to functions with the pointer format. The last describes a function that does both as shown.

CONSTANTS, ENUMERATED DATA TYPES & VOLATILE VARIABLES Constants must be initialized emmediately they are declared or this will result in a syntax error Defining constants with */#define #define A 1.5 /* note that A is of no particular type Better ways of defining constants are:*/ const int A=5; // can only be changed where you defined it but cannot be changed by or within the program volatile int B=6; // can be changed by something external to the program enum colors{cyan=7,blue,green=5,red};/* enumerated constants..sets cyan to 7, blue to 8, green to 5 and red to 6 i.e the uninitiated constants count upward frm the previous one, if 1st one uninitiated it is given a value of 0. note: this also declares a new data type called colors (similar to classes) with members cyan,blue,green & red. However the difference between this and classes is that objects of this data type can only take values which are the members. e.g within main;*/ colors my_color=blue; /* declares an "object" of colors and sets it value to blue which =7

POINTERS & INDIRECTION MEMORY Is in form of an ordered sequence of storage locations called memory cells. Each cell has a unique address. Data stored i a memory cell is called the contents of the memory cell. One memory cell is 8 bits (1 byte) POINTERS A pointer is a variable that holds a memory address. The address held by the pointer is the location of some other variable(with a specific value) in memory (indirect reference/ indirection). When variable1(e.g i.e the pointer) contains the memory address of variable2, it is said that variable1 points to variable2 DEFINING*/ data_type *name;

/*e.g*/int *myPtr1, *myPtr2;/*

INITIALIZING/ASSIGNING ADRESSES TO POINTERS*/ int *i; // *i is the content of the address stored in i (which is nothing) // i is the address of the content stored in *i (also nothing) int j = 25; // j is the content (i.e 25)

i = &j; cout<<&*i<<*&i; int *newptr newptr = i

// // // // // /*

&j is the address of the content of j *i is as described above (now = j = 25) i is as described above (now = &j = address) prints the same address twice..shows that * and & are inverses of each other & hence cancel out defined a new pointer newptr now points to the adress held in i, i.e adress of j and the content is j

Note: In the above example, if the content of i is given a new value i.e *i = 100; the content of the variable j is also changed i.e j = 100 (25 has been overwritten) Note: pointers must point to a value of same type but a void pointer can be assigned the value of any other pointer type Note: Also if another pointer variable int *x had been defined and initialized as x = i; x now holds the address of the same content as i and hence has the same content as i and &j. Note: You can initialize either the address or content of the pointer i.e*/ i = &j; or *i = &j/* BUT always give it a value of 0, NULL or an address (as above) i.e*/ *i=0; *i= NULL;/* SOME POINTERS TYPES Note that in general a pointer of a particular type can only point to the adress of a variable of the same type.*/ /*i.e*/int j=25; double *i= &j/*will give an ERROR!*/int j=5; int *jptr=&j; double *newptr=jptr/*also an ERROR! Void Pointer This is the only type of pointer that can point to any valid data type e.g*/void *xptr; int x=7; xptr=&x;/* Howevere such a pointer cannot be dereferenced i.e*/x=*xptr+7/*ERROR! Constant Pointer Cannot change the adress stored in the pointer(i.e the direction)e.g*/char *const name="john";/*char pointer to char array Pointer to a Constant Cannot change the content of the adress stored in the pointer e.g*/const char *name="john";/*char pointer to char array Pointer to a Pointer*/ char a='z'; char *b; char **c; //a;char variable, b;char pointer to 1 char variable, c;char pointer to 1 char pointer b=&a; c=&b; /* c holds the adress of pointer b, which holds the adress of variable a, which holds a character. Pointer to a Function It must have the same return type as the function it is pointing to & the same input type, & it is declared similar to a function prototype i.e before int main().*/ funct_retrn_typ(*funct_pointer_name)(funct_inp_typ); int main() { funct_pointer_name=function_name; // note no & symbol funct_pointer_name(x,y); // use the function pointer the same way you would use the function itself

}/* POINTER ARITHMETIC It is limited to addition and subtraction & all arithmetic is done relative to the base-type of the pointer e.g 1*/ char ch = 'c'; char *p = &ch; // p holds the address of ch and the content is c. p++; // p now holds the address of 1 memory cell after the address of ch and has the same content as that cell int x = 100; int *p = &x; // p holds the address of x and the content is 100. p++; // p now holds the address of 4 memory cells after the start address of x which itself takes 4 memory cells // int 1 and int x take up 32 bits = 32/8 = 4 memory cells each) p = p+10 // p now holds the address of 40 memory cells after its previous address ( int 10 = ten (int 1)'s which /* takes up 10 x 4 = 40 memory cells) e.g 2*/ char str[80]="Kings"; char *p; p = str; printf ("%c\n", *(p+4)); // gives s printf ("%c\n", *(&str[0]+4)); // gives s printf ("%c\n", str[4]); // gives s printf ("%c\n", *(&str[0])); // gives K printf ("%c\n", *(&str[1]+2)); /* gives g

ARRAYS OF POINTERS DEFINING*/ data-type *name [size] /* INITIALIZING e.g arrays of character pointers **see 'C' pointer notes! FOR FIGURES RELATING TO POINTERS PLEASE SEE 'C' NOTES

DYNAMIC MEMORY ALLOCATION This is when variables are created dynamically as they are needed while the program is running i.e at run-time stage, unl static memory allocation in which memory is assigned at compile stage. This requires the use of the */new/* keyword

REQUESTING DYNAMIC MEMORY*/ int *pointer; // declares a pointer. does not point to anything so no memory cells allocated to it yet. pointer= new (nothrow) int[5]; // there is now a total of 5 memory cells(4 bytes each) allocated to pointer. this can be seen /* like a pointer pointing to an integer array of 5 elements, which has not been initialized yet. OR*/ pointer=new (nothrow) int; // only allocates 1 memory cell(of 4 bytes) to pointer; like it is pointing to an integer variable // nothrow optional but allows us to deal with unsuccess manually as shown: if (pointer==0) // memory may not be available so check manually if request was successful or not {statements;} . . delete []pointer; /* the '5' memory cell allocation should be removed once it is not needed to free up memory space. OR*/ delete pointer; /* for a '1' memory cell allocation note; can also perform arithmeic within brackets during DMA e.g*/char *my_string; my_string=new char[strlen("abc")+1]/* the pointer variables are still available and can still be used, we have only deleted the memory alloacation! ARRAYS DEFINING 1-D input-type name[no_of_elements]; /* 2-D input-type name[no_of_rows][no_of_colums]; note: if no of elements not specified, the initializers determine it. however at least the no. of colums (rightmost index) must be specified for 2-D. INITIALIZING 1-D int a[3] = {6,8,3},int n[2]={0}; ACCESSING/REFERENCING ELEMENTS 1-D */ a[0]=6, a[1]=8, a[3-1]=3, n[0]=n[1]=0 */ /*..etc.

2-D 2-D float b[2][3] = {{1,2,4},{3,5,4}}; b[0][0]=1, b[0][1]=2, b[2-1][2]=4 this is listed row by row i.e row 0: 1,2,4 & row 1: 3,5,4 note: if not enough initializers, rightmost elements become 0.

i.e it starts from the 0th row for 1-D arrays and from the 0th row & 0th column for 2-D arrays. Can be used to print,initia or ask for individual elements as shown bel

note: for loops are often used to iterate through arrays; nested for loops for multidimensional arrays. e.g if you want t ask the user to input values for an large array, you do not want to do this element by element but instead using a loop. SETTING ARRAY SIZE WITH CONSTANTS You may want to do this so that if there are for loops within your program e.g for(i=o;i<size;i++), if you wanted to change the program for a different size of arrays, you will not have to update every loop in the program, but only change where you have initialized the constant 'size'. */ const int size=10; int A[size]; /* note only constants can be used to specify array size

STRINGS/CHARACTER ARRAYS C-style: same as above except; -character must be put in quotes & -when defining a 1-D array that will hold 3 characters, you must define it to hold 4 characters because the compiler inserts the null character '\0' automatically. For a 2-D array that will hold characters in 2 rows and 2 columns, you must define it to hold 2 rows and 3 columns as '\0' will be inserted at the end of each row making an extra column. e.g*/ name[0][1]='i' char name[3][8] = {{"Kings"}, {"College"}, {"London"}}; /* C++style: Make use of the built in string data type; must include the library */#include<string.h> string name= "Kings College London";/* BUT this is a single row character array!!!*/name[1]='i'/* PROPERTIES OF AN ARRAY NAME the name of an array without the index returns the address of the 1st element in the array.. i.e for the array called 'name' above, name is equivalent to &name[0].. (& is the address operator!) name+1 is equivalent to &name[1] etc.. i.e AN ARRAY NAME IS A POINTER to the 1st elemnt of the array PASSING ARRAYS TO FUNCTIONS */ int myArray[24]; myFunction(myArray,24) // myArray is passed by reference. size i.e 24 is passed by value e.g myfunction(int b[],size); myFunction(myArray) // myArray is passed by reference, no need to pass size e.g myfunction(int *b); myFunction(myArray[3]) /* passes an individual element of the array by value e.g myfunction(int x); note the earlier describes passing an array to the functions designed to accept arrays BUT an array can be passed to the function with the pointer format since the name points to the 1st element in the array as shown in the 2nd example. and the last describes passing individual elements of the array to a function designed to accept variables

FUNCTIONS BUILT-IN FUNCTIONS Some functions are contained within libraries which you must load before starting the program in order to use them in the program. Library & content Description*/

/* note if you use #include <iostream> or any other library, then below it, you have to inlcude the statement*/ using namespace std;/* where std is the namespace that contains the standard output and input (screen & keyboard) for use with the functions in this library, and the*/using/* keyword below selects this namespace. Alternatively, the namespace can be selected individually for sepcific functions e.g*/using std::cout; using std::setw;/*etc..which are put under the relevant include statment*/ #include <iostream.h> // this loads the input-output library; do not put a colon; at the end! (also called the processor!) cout << ; // prints the string of texts within "QUOTES" or variable after the stream insertion operator << cout << "x and y are" << x << "\t" << y << "and sum is equal to" << x+y; cout << "address of a is" << &x // prints the address of variable x cout << "A is" << A[0][1]; // where A is a multidimensional number or character array cout << "B is" << B; // where B is a SINGLE ROW CHARACTER ARRAY e.g B[]={"abc"}; cout << "adress of D is" << D; // Where D is a NUMBER ARRAY..prints the adress of D cout << "content of xptr" << *xptr // where xptr is a pointer to x e.g int *xptr; xptr=&x; cout << "address in xptr" << xptr // prints address of the variable stored in xptr i.e address of x cin >> ; // expects user to input a value to the variable appearing after the stream extraction operator >> cin >> x >> y; cin >> A[0][0] >> >> A[0][1] >> B[0][1]; // where A & B are multidimensional no. or char arrays cin >> C; /* user expected 2 input a string for a CHAR ARRAY e.g c-style;char C[4]; user types abc e.g c++style; string C; user can type ....abcd.... etc (note: no spaces when inputt note: with both C-style and C++ style strings, a space between inputs terminates the input to C and stores the rest in bu next call of cin for C or any other character array uses the remaining characters stored in buffer. If you would like to user to input with spaces then use the getline(); command described below, but only for C++ style strings*/ cin.get(); endl; sizeof(); precision(); // expects user to input one character, can be used within other statements; while etc e.g*/ char grade; grade=cin.get() // user types A /* works in the same way as \n when used with cout e.g*/ cout << x << endl; /* gives the memory size of a data type or created data type(class) e.g*/ sizeof(int); sizeof(className); /* determines the max no. of digits to be printed after the insert operator << e.g*/ double a=3.1415926534; cout.precision(3); cout<<a; // prints 3.14; similar to the one under iomanip /* when used with keyword*/fixed/*it only controls the fractional part*/ double a=3.1415926534; cout.precision(3); cout<<fixed<<a; // prints 3.141; again similar to " " " // This can be used to skip a specified number of values/characters during input(1 by default) e.g cin.ignore(); cin>>x // skips the first value/character the user types cin.ignore(3);cin>>y /* skips the first 3 values/characters the user types*/

ignore(x)

#include<stdarg.h> // standard argument library; contains functions & keywords for creating functions with variable arguments va_list ParameterList;

va_start(ParameterList,number); va_arg(ParameterList,argument_type); va_end(ParameterList) // all explained under creating user-defined functions with variable number of arguments #include <string.h> string mystring

// // getline(cin,mystring);// // strcpy()

creates a C++ style string variable called mystring as described under data types or character arrays note: C++ style strings do not end with the null character! similar to cin>>mystring where mystring is a string(single row character array,c++style) EXCEPT you can input spaces without any problems

strcat()

// copies one array of characters or string to another (and deletes the original!) // note: you have to take into account the sizes of the string being copied and the null character or some // data may be lost when copying. e.g*/ strcpy(my_string, other_string); // copies other_string into my_string char *my_string=new char[3];strcpy(my_string,"ab");// puts a,b & null character in 3 dnmiclly all. field // concatenates (or adds) two strings together e.g*/ mystring=strcat("a and ","b"); // gives a string "a and b" within mystring strcat(mystring,"plus") // adds "plus" to whatever is in mystring // returns the size of mysrting where mystring is a c++style string. // same as size() /* same as length(). Can also use like so;*/ strlen("abc");// returns 3

mystring.size(); mystring.length(); strlen(mystring);

sentence.find("word") // begins searching from the first defined C++ string and finds the first "word" int firstWord=sentenc.find("word"); // finds the 1st "word" int secondWord=sentence.find("word",firstWord+1);/* finds the "word" after the first "word" note: it finds the "word" even if it is within other words e.g swords; it picks out "word" Note: String arithmetic can be performed with C++ style strings e.g*/ string firstname="Joe", lastname="M", fullname=firstname+lastname; cout<<fullname;// prints Joe M #include <stdlib.h> itoa(integer_value,string_name,base) // is used to change an interger from base 10 to another and convert it into a C style string; // where base=10 for dec, 2 for binary, 16 for hex e.g itoa(5,my_string,10);// gives "5" in my_string itoa(5,my_string,2); // gives "101" in my_string #include <iomanip> // used to MANIPulate the output by printing values where we want in an imaginary array field on the screen. setw(n) // creates an imaginary array field with size n(i.e n cells)

// these are NOT memory cells, just output cells on the screen which guide where we want to print our values. cout<<setw(13)<<"value"<<endl; // creates a field of size 13 as such; [][][][][][][][][v][a][l][u][e] int n[2]={0}; // 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 9 10 11 12 13 for(int i=0;i<2;i++) // [][][][][][][0][][][][][][][][][][][][][0] {cout<<setw(7)<<i<<setw(13)<<n[i]<<endl;}/*[][][][][][][1][][][][][][][][][][][][][0]doesnt print boxes! Note: when setw is used more than once, it creates fields next to each other unless endl or \n is used.*/ setfill('n') /* fills(with characters) the unitialized spaces in an imaginary array field created by setw e.g*/ cout<<setfill('x')<<setw(10)<<77;// [x]][x][x][x][x][x][x][x][7][7] doesnt print boxes! setprecision(n) // determines the max no. of digits to be printed after the insert operator << double a=3.1414; precision(3); cout<<a;/*OR*/cout<<setprecision(3)<<a; // prints 3.14 /* when used with keyword*/fixed/*it only controls the fractional part*/ cout<<fixed<<setprecision(3)<<3.1414; /* prints 3.141 NOTE: Alot of these built in functions can be used with classes & objects as has been described in a few places above, an example is shown below*/ strcpy(mystring,object.mystring); /* use for example within a member function or copy constructor for objects USER DEFINED FUNCTIONS Functions that accept parameters by value*/ #include <iostream.h> return-type name(input-type var1,inp-typ var2) { function body (declaration, statements); return value/variable; }

// headers that contain other functions that will be used within yours // the type of data the function returns, function name // in the brackets define input variable(s) the same way as for a program // // // /* the function has a separate memory space for variables so, if you want to use a variable you have calculated in your function, you must return it to function main() but this is only for all non void functions. calculations can be performed with the return statement e.g return x*x

Passed parameters by value- when a variable is passed to a user created function, its value is copied to that function an hence the original value is not altered by the function and they are located within two separate memory spaces. Functions that accept parameters by reference*/ #include <iostream.h> return-type name(input-type &var1,inp-typ &var2) { function body (declaration, statements); return value/variable; } OR using pointer format*/

// note the & operator. Also, it can be made to accept one or more values by // reference and others by value if required. call like so; name(var1,var2); // return may not be required if the purpose of the function is to alter the /* variable passed to it. leave out or use- return;

return-type name(input-type *var1,inp-typ *var2)

/* call like so; name(&var1,&var2);

Passed parameters by reference- In this case the function has access to the memory space of the variable passed to it and can alter its value in both the user created function and the calling function. not: The value/variable returned must be of the same tyoe as return-type. If return is not required then leave out or use Functions that accept arrays*/ return-type name(input-type arrayname[], inp-typ arraySize) return-type name(input-type arrayname[][])

// accepts a 1D array, note: array size not neccessary /* accepts a 2D array

You can fill in the square brackets with the exact dimensions you want the input array to be. If the content of an array is changed in a function, it is changed in the main as well i.e arrays are passed by referenc note: your functions can be used within other functions or program flow statements (if, while etc) and the value returned from your function is what is used. note: functions can call other functions.. hence placing of the function within the program is important. DECLARING THE FUNCTION 1.) The function can be declared and initialized after the include header statement (b4 the main function) like so:*/ #include <iostream.h> float square (float x) // note: no semicolon! (we have used passed by value in this example) { return x * x; } int main() float z=10.0; cout<<"z squared is"<<square(z)

/* prints z squared is 100 (since square(z) returns z squared) but z still=10

2.) The function prototype can be placed emmediately after the include statement (b4 the int main function), and the function can now be initialized before or after the main function like so: */ #include <iostream.h> float square (float &); // function prototype; note the semicolon! (we have used passed by reference in this) int main() { float z = 10.0; square(z); // passed by reference, z is now z squared=100 cout<<"z squared is" << z; // prints z squared is 100

return 0; } float square (float &x) { x= x * x; } // initializing the function; note: no semicolon! // even though it says 'x', it is changing the value of z since x now refers to z. /*

3.) The prototype of the function can be placed in a header file which can be included at the beginning with the other header files, the advantage is that many prototypes can be put in one header file. The example below doesn't relate to the this but is here to show the function protoype for those accepting arrays*/ #include <iostream.h> float square (float [], int); /* function prototype; note the semicolon! int is for the array size which is not necessary as said before... etc DECLARING THE FUNCTION with DEFAULT ARGUMENTS Default variables can be specified in either the function prototype or the function header. Doing this allows the function to be called by less or no input arguments than it is designed for, & if this is done, it assigns default values to variables which are not initialized when the function is called; rightmost unitialized values are defaulted. */ int boxVolume(int L=1, int W=1, int H=1);/* prototype;default initializers can be constants/global variables/function calls. DECLARING THE FUNCTION with a VARIABLE NUMBER OF ARGUMENTS*/ void nothin(); /*OR*/ void nothin(void); // accepts nothing and returns nothing

/*need to include the library*/#include<stdarg.h> void display_var(int number, ...); // number is the required input that reps the names of the inputs that will be accepted. int main(){int one=1; dsiplay_var(one,3); return 0;} // int main has been used to call the function with 2 input arguments void display_var(int number, ...) { va_list ParameterList; // keyword va_list; used to define variable "ParameterList" that will accept parameters va_start(ParameterList,number); /* va_start is a function that accepts variable that will hold your parameters and checks and assigns it the amount of input parameters; called "number" that have been use call your function; it stores this amount in a variable called number*/ for (int i=0; i<number; i++) {cout<< va_arg(ParameterList, int);}/* va_arg is a function that the parameter-holding-variable, and the type of parameters tha your function accepts, and assigns your function the parameters via ParameterLis cout here is not necessary and only prints out the parameters that have been ext va_end(ParameterList); /* closing macro INLINE FUNCTIONS

Used for speeding up the program, it replaces/copies the function implementation directly to main() whenever it is called of exiting main(). A big disadvantage is that it uses more memory*/ inline rtrn-type name(inpt-typ var1, inpt-typ var2) { function body; return value/variable; }/* Best not to use inline functions! FUNCTION VARIABLES Local variables- if a variable 'x' is defined in the main function, and 'x' is also defined in the user created function, both variables are stored in separate spaces and are NOT the same.. 'x' from the function can only be used in the main function if it is returned by the function. Global variables- this is not defined within any function(main or user created) but before any function is called (but after include statement). The variable is visible to and can be used by any function. e.g it is best to define const variables this way such a pi=3.142 note: if a globale & local variable are defined with the same name, the local variable will take priority within the function it is defined in. To use the global variable within this function e.g with cout, is done like so: */ cout <<"the local variable is" << x <<"\n"; // prints the local cout <<"the global variable is" <<::x; /* prints the global FUNCTION OVERLOADING Functions can have the same name but must have different parameter types or a different no of parameters or both*/ int square( int x ); // accepts and returns values of type int double square( double y ); // accepts and returns values of type double /* in order to call the right one, the function must be called with a value of the same type as the function parameter. output type OR with the correct no. of input parameters e.g*/ int a, int numberSquared= square(a);/* calls int square function*/double ans=square(7.5);/* calls double square function RECURSION This is when a function calls itself several times until a specific condition is met. e.g1 a recursive factorial function; where n!=1x2x...xn and 0!=1!=1 */ int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n-1); }/* Hence by implementing the function as above we work out that for example 4!=4*3!=4*3*2!=4*3*2*1!=4*3*2*1; i.e main calls the function for factorial(4); which first return; (4 * something1) to main(); Then main() calculates "something1" by calling the function next for factorial(4-1);

So up to now we have; (4 * (4-1) * something2) This goes on until we have; (4 * (4-1) * ([4-1]-1) * ([[4-1]-1]-1) * something_final) The calculation of "something_final" involves calling the function for factorial(1) which returns 1. Hence we have; (4 * (4-1) * ([4-1]-1) * ([[4-1]-1]-1) * 1)= 4*3*2*1 = 24 In summary, most recursive functions have at least two conditional statements or two "checks" of any form; One that calls the function continuously for a decremented/incremented input value, And one that performs a single command (e.g returns a value) without calling the function when the input value is decremented/incremented to a particular point. e.g2 a recursive power function*/ float raised_to_power(float number, int power) { if (power < 0) { cout << "\nError - can't raise to a negative power\n"; exit(1); } else if (power == 0) return (1.0); else return (number * raised_to_power(number, power - 1)); }/*

PROGRAMS BASIC PROGRAM TEMPLATE This should be used as a skeleton for all your written programs*/ #include <iostream> using namespace std; int main() { cout<<"hello world\n"; cin.get(); cin.get(); return 0; } // // // // // // /* // /* you can include as many headers as you want that contain useful functions explained above under libraries function main begins program execution & int tells main to return an integer value starts the body function main body of the prog. which may contain several functions or other necessary material still part of the body, this use of cin.get twice is to freeze the output as was done.. ..with*/ scanf("%d");/* in C. OR */system("pause");// command may be used used to terminate the program emmediately end function main

CONTROLLING PROGRAM FLOW if selection*/ if(expression) { statement(s); } default statement(s) if/else selection*/ if(expression) {statement1;} else if(expression) {statement2;} else {statement3;}

// if this condition applies // do this /* do this whether the condition applies or not

// if this condition applies // do this // if 1st condition doesnt apply but this one does // do this instead /* if non of the conditions apply, do this.

note: can have infinite else if statements. nested if's*/ if(expression) { if(expression) statement(s); else statement(s); } else statement(s); } // if the abova(1st if) condition doesn't apply // do this /* // // // // check if this condition also applies do this if the above(2nd if) condition doesnt apply do this instead

// if this condition applies

Note: if(0) returns false and the statement will not execute & if(5) returns true & the statement executes Note: you dont need to use braces if you only have 1 statement (on one line) within if, else, or elseif while loops*/ int i=0; while(expression involving i) { statement(s); i=i+1; }

// usually requires a counter, initialize now! // while this condition applies // do this as long as the above condition applies // or a similar expression to update the counter /* return to the start of the loop and test the condition again

for loops*/ int i; // usually requires a counter BUT DO NOT initialize now! for(i=0;expression involvin i; i++)// initialize counter; test if expression is true;(update counter; NOT YET!) { statement(s); // do this as long as the above condition applies; (NOW update counter) } /* return to the start of the loop and test the condition again for loops with more than 1 counter*/ int i,j; for (i = 0, j = 0; j + i <= 10; j++, i++) { printf( "%d\n", j + i ); } /* the output is 0, 2, 4, 6, 8, 10 nested for loops*/ for (int i = 0 { for (int j = 0; j < 6; j++) printf("%d\n", i*j); printf("***********\n"); }

// // // // /*

j increases from 0 to 5 and i*j is printed each time (inner loop) stars are printed once(outer loop) the above sequence repeats for i=1,2,3...6 outputs 000000 (stars), 012345 (stars), 02468 10(stars) etc upto 0 6 12 18 24 36 (stars)

note: 'i' and 'j' can be defined and initialized inside brackets as shown in the nested example note: the counter may update before or after the statement depending on whether you use ++i or i++ or similar expressions note: for and while loops test the condition at the top of the loop, which means that the loop may not execute at all i.e if the loops continuation test(expression involving i) is intially false do-while loop */ do { statement(s); } while (condition);

/* note the smicolon after the condition of the while statement

note: 'do-while' test the condition at the end of the loop, which means the loop will execute at least once switch statement*/ switch (expression) { case constant_1: statement(s);

// expression MUST evaluate to either an integer or character value // e.g of constant; 25, 'r','R'. If this case matches expression result // perfom this statement and

break; case constant_2a: case constant_2b: statement(s); break; case constant_n: statement(s); break; default: statement(s); }

// // // //

break terminates the program immediately if the above statement didnt match, statment above is not performedand this is tested instead; note can have more than 1 case per statement as shown

// etc until one matches, break is encountered and it terminates

// If no constants match, the statements following default are executed// Default statement is optional /*

break statement Used within the switch statement & can be used within while & for loops especially to end an infinite loop*/ for ( ; ; ) /*or*/ while(1) // infinite loops { statement // always!! do this if (statement) // and always check this break; // end infinite loop when if statment fulfilled } statement /* now perform this statement continue statement when used after a statement within the loop, it skips the remaining statements in the body of a while, for or do-while loop & Proceeds with the next iteration of the loop (i.e starts again from the beginning while and dowhile Loop-continuation test is evaluated immediately after the continue statement is executed for Increment expression is executed, then the loop-continuation test is evaluated return Statement*/ return expression; /* note: expression is only present if the function specifies a return type If expression is omitted, return statement simply causes control to revert back to calling function The goto Statement*/ char ch; point1: ch = getchar();

// label for go to statement

if (ch != 'A') goto point1;

// go to label now! if condition applies, if not, continue with rest of program /*

printf("You typed an A\n", ch);

note: A label must appear in the same function as the goto statement that refer to it use of goto is NOT recommended - which tends to encourage logic that skips all over the programstructured in orderly and sequential manner.