User Tools

Site Tools


opus:spring2012:cforman:cprogpart3

cprog Keywords

Functions, Parameters(pass by: value, Address, Reference), Return Types, Recursion

Functions are something a programmer will use everyday. We use them and create them whenever we do something with a program. Each program we make is essentially a function, whether we pass it parameters or not its a function and can be adjusted to work inside any other function. example in C

 #include <stdio.h>
  2 #include <stdlib.h>
  3 int subtraction(int *a1, int *a2,int);
//I then call this function called "subtraction" later on in my devision part of the program and this is used as a function. 

266 int subtraction(int *arr1, int *arr2,int sizea)
267 {
268     int l,i,a,b,c,p;
269     l=i=a=b=c=p=0;
270     while(!(*arr1 <= 0))
271     {
272         i=sizea-1;
273         for(l=sizea-1;l>=0;l--)
274         {
275
276             a = arr1[i];
277             b = arr2[l];
278             if( a >= b )
279             {
280                 a = a - b;
281             }
282             else if( (a < b)&&(arr1[i-1]>0))
283             {
284                 c = arr1[i-1];
285                 c = c - 1;
286                 arr1[i-1] = c;
287                 a = a + 10;
288                 a = a - b;
      }
290             arr1[i] = a;
291             i=i-1;
292         }
293         p=p+1;
294     }
295     return(p);
296 }

what this did was take information given and send it to a function that would act within the program and would return a result. It does not always have to return anything but this one did. The one thing you may notice is that i sent something into the subtraction program. I am sending paramaters for the program to act on. Two ways they can be sent is by value and by reference. Value is when we send the function a straight up variable, this is when we sent it “int sizea” that was by value. The next kind i used was by reference “int *arr1” this was sending it the array called “arr1” and sending all the pieces of it not just one part. The star declares that it is by reference. The next kind is when we pass something by address which is when we send the computer a hexadecimal digit representing a particular zone in memory.

The return type can be seen within the program. Line 295 above shows that I am returning the variable “p” which is an int. You can return anything back to the original but you can only return one thing to it so be specific on what you want to send out. There is no limit to what you can send out besides the fact that it must be one thing(can be int, char, long int, void, float ex…).

Recursion— bassically something that will run itself over and over again… here is an example of code from http://www.cprogramming.com/tutorial/lesson16.html

#include <iostream>

using namespace std;

void recurse ( int count ) // Each call gets its own count
{
  cout<< count <<"\n";
  // It is not necessary to increment count since each function's
  //  variables are separate (so each count will be initialized one greater)
  recurse ( count + 1 );
}

int main()
{
  recurse ( 1 ); //First function call, so it starts at one        
}

• Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)

Definition

Compiler is a program that will take your script and convert it into runnable code. gcc or g++ ( one i used recently “gcc -g -o bignum bignum.c” )

Preprocessor allows for the use of header files and checks for errors during before compilation to make sure the program will run. -Wall can be added to the line above to allow the preprocessor to check for warning and not just flags.

Flags are the easiest things the the preprocessor can spot because they are errors like missing “;” or trying to use a char as an int or something that the user may mistake and can be solved easily.

The Assembler is the part of the computer that takes a program written in source code and compiled then translated int to assembly language and then to matching code so that it can be used.

The linker is the final part of the compiler where it takes the source codes from multiple pieces and combines them into one executable file. Usually we have only used it to take one source code and create one program but it can do this to many pieces of source code and combine them into one executable.

Multi-file programs - usually its best to create a separate directory for a multi filed program as it is easier to work with.

lab46:~/src/cprog/c++/sampleprogs/abtractbaseclass$ ls
abstractbaseclass.cc  and.h  friends  gate.h  main.cc  nand.cc  nand.o  or.h  origabstractclass.cc  xor.cc  xor.o
and.cc                and.o  gate.cc  gate.o  main.o   nand.h   or.cc   or.o  program               xor.h
lab46:~/src/cprog/c++/sampleprogs/abtractbaseclass$

to compile this we first take the original say “gate.cc” and extract the definitions form it and make them into a header file “gate.h” after that we can convert the .cc file into a .o by using “g++ -c gate.cc” then to combine all the .o files we use “g++ -o program and.o gate.o main.o nand.o or.o xor.o ”

• Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]

Definition

Classes allow for data to be sent in and sent out it makes it easy to define variables in multiple parts of functions like the program in the keyword above uses classes to allow for easy creation of variable so that the same data doesn't have to repeated a hundred times.

objects in a class are the pieces that are being used in the other functions in relation to that class.

Constructor creates the object for the moment that it is called and after its use is deconstructed by the deconstructor when no longer needed.

Access control can be summed up by what the child program cant do and can do. the child program is the program that uses objects created by the class. Remember the child can access its parents public and protected objects but it cannot touch its parents privates.

Public - is data that any part of the program can access and manipulate.

protected - is data that only designated parts can access but usually allows for all child programs.

private - is only data accessible within the class itself and cannot be accessed by any other part unless you got a friend.

friend - creating a friend is like giving a person the permission to stick his hand into your parents private when related to programming. A friend can bypass the security of a class and access the private parts of the class so the child program can use that data.

“This” pointer type - from lack of a better way to put it “ The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a nonstatic member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x. You cannot declare the this pointer or make assignments to it.” by http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr035.htm

#include <iostream>
using namespace std;

struct X {
private:
  int a;
public:
  void Set_a(int a) {

    // The 'this' pointer is used to retrieve 'xobj.a'
    // hidden by the automatic variable 'a'
    this->a = a;
  }
   void Print_a() { cout << "a = " << a << endl; }
};

int main() {
  X xobj;
  int a = 5;
  xobj.Set_a(a);
  xobj.Print_a();
}

from same place

• Inheritance (single, multiple Inheritance), Polymorphism/Virtual Functions, Abstract Base Class [C++]

Definition

Inheritance - is when you create a child program it receives the data from the class and uses it as its own.

 class NAND:public GATE{
  7     public:
  8         NAND();
  9         void process();
 10 };

multiple inhertance is like inheritance of a single class but from multiple parents to one child …. yes there can be more then 2 parents. http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr134.htm (Table below)

class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };

Polymorphism - takes the idea of a type pointer in one class and turns it back on the parent class as they share the same type pointer as the parent. script from http://www.cplusplus.com/doc/tutorial/polymorphism/ because ours was really long and i missed that day so i have photos and not program.

// pointers to base class
#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
  };

class CRectangle: public CPolygon {
  public:
    int area ()
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area ()
      { return (width * height / 2); }
  };

int main () {
  CRectangle rect;
  CTriangle trgl;
  CPolygon * ppoly1 = &rect;
  CPolygon * ppoly2 = &trgl;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  cout << rect.area() << endl;
  cout << trgl.area() << endl;
  return 0;
}

An abstract base class is like “class person” with the objects that define it more as age and height. its non-specific or vague concept

Overloading (Functions, Operators) [C++]

Definition

when you overload a function you have two functions with the same name but different parameters and by calling that program it will dicide which one to choose based on the parameters that you feed it.

when you overload an operator you

Demonstration

Demonstration of the chosen keyword.

If you wish to aid your definition with a code sample, you can do so by using a wiki code block, an example follows:

/*
 * Sample code block
 */
#include <stdio.h>
 
int main()
{
    return(0);
}

Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:

lab46:~$ cd src
lab46:~/src$ gcc -o hello hello.c
lab46:~/src$ ./hello
Hello, World!
lab46:~/src$ 

Templates, STL (Standard Template Library) [C++]

A template is like a stencil or outline of a program. difference is a template is not specific until it is given data then it will choose which program to run that matches the template.

 template <class T>
  2 T larger(T x, T y)
  3 {
  4     if (x >= y)
  5         return (x);
  6     else
  7         return(y);
  8 }
  9
 10  int main()
 11 {
 12     int a=12, b=17;
 13     float c=3.14,d=1.59;
 14     char e=65, f='A';
 15
 16     cout<<larger(a,b)<<endl;
 17     cout<<larger(c,d)<<endl;
 18     cout<<larger(e,f)<<endl;
 19 return(0);
 20 }
 21
 22

STL - contains many of the basic algorithms and outlines for the programs used in C++

• Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]

Definition

type casting operators -

Demonstration

Demonstration of the chosen keyword.

If you wish to aid your definition with a code sample, you can do so by using a wiki code block, an example follows:

/*
 * Sample code block
 */
#include <stdio.h>
 
int main()
{
    return(0);
}

Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:

lab46:~$ cd src
lab46:~/src$ gcc -o hello hello.c
lab46:~/src$ ./hello
Hello, World!
lab46:~/src$ 

• Exception Handing (throw, try, catch) [C++]

Definition

an exception is a way of dealing with odd circumstances in our programs by surrounding a block of text in the block called “try”

int main()
{
   try
   {
      throw 10
   }
   catch(int k)
   {
     printf("an exception has happened %d\n",e);
   }
   ...

the idea of using this is to have the throw be within your program inside of try so you want to put your whole program in try. Then the variables that are getting lost you check with catch( variable type) and then output what is getting lost or if it isnt.

1
2
3
4
5
6
7
8
9
10
11

	

try {
  try {
      // code here
  }
  catch (int n) {
      throw;
  }
}
catch (...) {
  cout << "Exception occurred";
}

cprog Objective

cprog Objective

State the course objective

Definition

In your own words, define what that objective entails.

Method

State the method you will use for measuring successful academic/intellectual achievement of this objective.

Measurement

Follow your method and obtain a measurement. Document the results here.

Analysis

Reflect upon your results of the measurement to ascertain your achievement of the particular course objective.

  • How did you do?
  • Is there room for improvement?
  • Could the measurement process be enhanced to be more effective?
  • Do you think this enhancement would be efficient to employ?
  • Could the course objective be altered to be more applicable? How would you alter it?
opus/spring2012/cforman/cprogpart3.txt · Last modified: 2012/05/09 23:35 by cforman