Table of Contents

Part 2

Entries

October 7, 2011

October 9, 2011

Working on Keywords today, including: Multi-Dimensional Arrays, Multi-file programs, Code stages (Source, Object, Binary) .

October 17, 2001

October 23, 2011

Cprog Topics

Multi-dimensional arrays

An Array having one dimension is called a 1 Dimensional Array.
An array with more than one dimension, is called a Multi-dimensional Array.
Specifically, an array having two dimensions is called 2D array, three dimensions is called a 3D, and so on.
In C programming an array can have two or three or four or even ten or more dimensions.

Without exception, all arrays in C are numbered from 0 up to one less than the bound given in the declaration,
the highest usable subscript is always one less than the one used in the declaration.

Multi-dimensional arrays can be defined as follows:
For two dimensions:

int Two_Dimensional_Array[8][8]; \\ 

For further dimensions simply add more [ ]:

int Multi_Dimensional_ArrayD[50][50][40][30]......[50]; \\ 

In the two dimensional example, think of it as a chessboard, To access it, all you need are two variables, one that goes in the first slot and one that goes in the second slot.
You can do many things with arrays, from storing information about certain things under one name, to making games like chess or checkers. You can use loops to access arrays.

Below is an example of a 3 dimensional array:

#include<stdio.h>
 
void main()
{
int a, b, c;
int arr[3][3][3]=
        {
            {
            {1, 2, 3}, {4, 5, 6}, {7, 8, 9}
            },
            {
            {201, 202, 203}, {204, 205, 206}, {207, 208, 209}
            },
            {
            {30000001, 30000002, 30000003}, {30000004, 30000005, 30000006}, {30000007, 30000008, 30000009}
            },
        };
 
printf(":::3D Dimensional Array Example:::\n\n");
for(a=0;a<3;a++)
{
    for(b=0;b<3;b++)
    {
        for(c=0;c<3;c++)
        {
        printf("%d\t",arr[a][b][c]);
        }
        printf("\n");
    }
    printf("\n");
}
 
}
lab46:~/src/cprog$ nano ThreeDarray.c \\ 
lab46:~/src/cprog$ gcc -o ThreeDarray ThreeDarray.c -lm \\ 
lab46:~/src/cprog$ ./ThreeDarray \\ 
:::3D Dimensional Array Example::: \\ 

1       2       3
4       5       6
7       8       9

201     202     203
204     205     206
207     208     209

30000001        30000002        30000003
30000004        30000005        30000006
30000007        30000008        30000009

Multi-file programs (how to structure, how to compile)

If a program contains many functions then it is difficult to read and maintain.
As the number of functions increases the size of the program/file will also increase.
To avoid this some functions can be written in separate file.
A large program can be divided into multiple files, plus a main program file.
This makes each file short enough to conveniently edit, print, etc.
It also allows some of the code, such as utility functions, linked list handlers and array allocation code, to be shared with other programs.
You can divide your code along natural divisions in the program.
Each file should contain a group of functions that do related things.
The individual files will be compiled separately and then linked together to form one executable object program.
This will help to editing and debugging because each file can be maintained at a manageable size.
To execute a multi-file program, each individual file must be compiled separately, then the main program file is compiled and executed.

The basic approach to dividing up a program into separate files is this:
Group together related program elements, and put each group of related declarations in one header file, and and each group of related definitions in a source file. When a source file refers to something declared in a header file, the #include directive is used to make the compiler scan the header file at the start of the source file.

To compile a multi-file program, first compile each of the non-main files of code.
To compile a program that has been divided across multiple source files:
Instead of typing: gcc -o executable sourcefile.c
you would type:

gcc -o executable sourcefile_1.c sourcefile_2.c ... sourcefile_n.c

Code stages (Source, Object, Binary)

All high-level language code must be converted into a form the computer understands. In C language, the source code is converted into a lower-level language called assembly language. The assembly language code made by the previous stage is then converted into object code which are fragments of code which the computer understands directly. The final stage in compiling a program involves linking the object code to code libraries which contain certain built-in functions. This final stage produces an executable program.

An Assembler is used to take text Source Code and turn it into Binary machine code.
More precisely, it turns the source into object code, which contains additional information like symbol names, relocation information etc.

A compiler is used to take higher-level language source code, and either directly turns it into object code, or (as is the case with GCC) turns it into Assembler source code and invokes an Assembler for the final step.

The resulting object code does not yet contain any code for standard functions called.
If you included, for example, <stdio.h> and used printf(), the object code will merely contain a reference stating that a function named printf() must be linked to the object code in order to receive a complete executable.

lab46:~/src/cprog$ nano inputdisplaynumber.c
lab46:~/src/cprog$ gcc -o inputdisplaynumber inputdisplaynumber.c -lm
lab46:~/src/cprog$ ./inputdisplaynumber
Enter any number: 54
Then mumber you entered was 54lab46:~/src/cprog$
#include <stdio.h>
 
int main()
{
int this_is_a_program_to_display_a_number;
 
	printf("Enter any number: ");
	scanf("%d", &this_is_a_program_to_display_a_number);
	printf("Then mumber you entered was %d", 	
        this_is_a_program_to_display_a_number);
	getchar();
	return 0;
}

C Library, Libraries, and Makefiles

The C Library, in the programming language C, describes a collection of headers and routines used to implement common operations such as input/output and string handling.
Libraries for use by C programs consist of two parts: header files that define types and macros and declare variables and functions; and the actual library or archive that contains the definitions of the variables and functions.
The C Library may refer either to an informal synonym for C standard library or a library which has an interface for linking to C programs.
The C runtime Library is used to refer to a set of base libraries, which may be distributed in dynamically linkable form with an operating system or distributed with a C compiler. The run-time support provides the C standard library functions and other material needed to create an environment for the C program, such as initialization before invoking the 'main' function, or subroutines to provide arithmetic operations missing from the CPU that are needed by code generated by the C compiler.
Note that header files from the C standard library should have the form headername.h when used in a C program, and the form cheadername when used in C++ programs (note the c as a prefix).
Some of these Header Files are:

  <ctype.h> : Character Class Tests
  <float.h> : Implementation-defined Floating-Point Limits
  <math.h> : Mathematical Functions
  <stdarg.h> : Variable Argument Lists
  <stddef.h> : Definitions of General Use
  <stdio.h> : Input and Output
  <stdlib.h> : Utility functions
  <string.h> : String functions
  <time.h> : Time and Date function
  

Makefiles are special format files that together with the make utility automatically build and manage your projects.
The makefile is composed of the following components: explicit rules, implicit rules, variable definitions, directives, and comments.
An explicit rule says when and how to remake one or more files, called the rule's targets. It lists the other files that the targets depend on, called the prerequisites of the target, and may also give a recipe to use to create or update the targets.
An implicit rule says when and how to remake a class of files based on their names. It describes how a target may depend on a file with a name similar to the target and gives a recipe to create or update such a target.
A variable definition is a line that specifies a text string value for a variable that can be substituted into the text later.
A directive is an instruction for 'make' to do something special while reading the makefile.
A ‘#’ in a line of a makefile starts a comment. It and the rest of the line are ignored, except that a trailing backslash not escaped by another backslash will continue the comment across multiple lines.
The include directive tells make to suspend reading the current makefile and read one or more other makefiles before continuing.

To prepare to use make, you need to write a file called the makefile that describes the relationships among files in your program and provides commands for updating each file.
The makefile has instructions for a specific project. The default name of the makefile is literally makefile, but the name can be specified with a command-line option.
In a program, typically, the executable file is updated from object files, which are in turn made by compiling source files.

lab46:~$ cd src
lab46:~/src$ gcc -o hello hello.c
lab46:~/src$ ./hello
Hello, World!
lab46:~/src/cprog$ gcc hello.c -o hello
lab46:~/src/cprog$ make hello.c - hello
make: Nothing to be done for `hello.c'.
make: `hello' is up to date.
lab46:~/src/cprog$

Version Control (checkout, commit, update, add, log)

A version control system is a system that tracks incremental versions or revisions of files and, in some cases, directories over time.
A version control system is useful in the fact that it allows you to examine the changes which resulted in each of those versions and facilitates the arbitrary recall of those changes if necessary.
At the core of the version control system is a repository, which is the central store of that system's data in the form of directories and files.
A version control system's value comes from the fact that it tracks versions of files and directories.
A very close secondary mission in any modern version control system is to enable collaborative editing and sharing of that data.
Subversion, CVS, and many other version control systems use a copy-modify-merge model.
Subversion implements the concept of a version control repository much as any other modern version control system would.
A Subversion client commits communicates the changes made to any number of files and directories as a single atomic transaction.
Each time the repository accepts a commit, this creates a new state of the filesystem tree, called a revision. Each revision is assigned a unique natural number, one greater than the number assigned to the previous revision.
Subversion client programs use URLs to identify each version of the files and directories in Subversion repositories.
A Subversion working copy is an ordinary directory tree on your local system, containing a collection of files.
You can edit these files however you wish.
After you've made some changes to the files in your working copy and verified that they work properly. Subversion provides you with commands to “add” or “publish” your changes.
For each file in a working directory, Subversion records (among other things) two essential pieces of information:
What revision your working file is based on (this is called the file's working revision).
A timestamp recording when the local copy was last updated by the repository.
To get a working copy, you must checkout some subtree of the repository.
svn checkout
To publish your changes to others, you can use Subversion's svn commit command.
To bring the project up to date, use the svn update command. This will incorporate your changes into the working copy, as well as any others that have been committed since it checked it out.
Every time you run svn commit your working copy ends up with some mixture of revisions. The things you just committed are marked as having larger working revisions than everything else. After several commits (with no updates in between), your working copy will contain a whole mixture of revisions. Even if you're the only person using the repository, you will still see this phenomenon. To examine your mixture of working revisions, use the svn status command. \

lab46:~/src/cprog$ svn commit -m "added base1"
Adding         cprog/base1.c
Adding         cprog/baseconvert.c
Transmitting file data ..
Committed revision 7.
lab46:~/src/cprog$

Structures

A structure is a collection of C data types which you want to treat as a single entity.
Structures are like arrays except that they allow many variables of different types grouped together under the same name.
These variables can be of different types, and each has a name which is used to select it from the structure.
Structures are a convenient way of grouping several pieces of related information together.
A structure can be defined as a new named type, extending the number of available types and it can use other structures, arrays or pointers as some of its members.
A structure type is usually defined near to the start of a file using a struct or a typedef statement.
The struct or typedef defines and names a new type, allowing its use throughout the program.
The struct or typedef usually occurs just after the #define and #include statements in a file.
Arrays of structures are a good way of storing lists of data with regular fields, such as databases.
For example:
A database could be used with a structure to hold information about a student:

#include<stdio.h>

struct student
{
   char *name, *college, *year;
   int age;
};

int main()

{
   struct student s;
   s.name = "John Doe";
   s.college = "Corning Community College";
   s.year = "Freshman";
   s.age = 19;
   printf("%s\n",s.name);
   printf("%s\n",s.college);
   printf("%s\n",s.year);
   printf("Student age = ");
   printf("%d",s.age);
   return 0;
}
lab46:~/src/cprog$ nano
lab46:~/src/cprog$ ls
lab46:~/src/cprog$ gcc -o structures structures.c -lm
lab46:~/src/cprog$ ./structures
John Doe
Corning Community College
Freshman
Student age = 19
lab46:~/src/cprog$

typedef, enum, union

A typedef allows you to introduce synonyms for types which could have been declared some other way.
The new name becomes equivalent to the type that you wanted.
typedef can make your code more clear and make your code easier to modify.

/*
 * Sample typedef
 */
#include<stdio.h>
 
typedef struct student
{
   char *name, *college, *year;
   int age;
} STUDENT;
 
int main()
{
   STUDENT s;
   s.name = "John Doe";
   s.college = "Corning Community College";
   s.year = "Freshman";
   s.age = 19;
   printf("%s\n",s.name);
   printf("%s\n",s.college);
   printf("%s\n",s.year);
   printf("Student age = ");
   printf("%d",s.age);
   printf("\n");
   return 0;
}
lab46:~/src/cprog$ nano
lab46:~/src/cprog$ gcc -o typedef typedef.c -lm
lab46:~/src/cprog$ ./typedef
John Doe
Corning Community College
Freshman
Student age = 19
lab46:~/src/cprog$

The enum type specifier is short for “enumerated data”. The user can define a fixed set of words that a variable of type enum can take as its value. The words are assigned integer values by the compiler so that code can compare enum variables.
Enums have these benefits:

  They restrict the values that the enum variable can take. \\ 
  They force you to think about all the possible values that the enum can take. \\ 
  They are a constant rather than a number, increasing readability of the source code. \\  

In C, the variable declaration must be preceded by the word enum as in:

#include<stdio.h>
int main()
{
    enum Day {Sunday = 1,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
    enum Day Today;
    int x;
    printf("please enter the day of the week (1 to 7), Sunday is 1 \n");
    scanf("%d",&x);
    Today = x;
    if(Today==Sunday || Today==Saturday)
        printf("Enjoy! Its the weekend\n");
    else
        printf("It's a weekday, make sure you do your homework !\n");
    return 0;
}
lab46:~/src/cprog$ nano
lab46:~/src/cprog$ gcc -o enum enum.c -lm
lab46:~/src/cprog$ ./enum
please enter the day of the week (1 to 7), Sunday is 1
1
Enjoy! Its the weekend
lab46:~/src/cprog$ ./enum
please enter the day of the week (1 to 7), Sunday is 1
5
It's a weekday, make sure you do your homework !
lab46:~/src/cprog$

Unions are like structures except they use less memory. If you create a structure with a double that is 8 bytes and an integer that is 4 bytes then the total size will still only be 8 bytes. This is because they are on top of each other. If you change the value of the double then the value of the integer will change and if you change the value of the integer then the value of the double will change.
A union is a structure in which all of the members are stored at the same address. Only one member can be in a union at one time. The union data type was invented to prevent the computer from breaking its memory up into many inefficiently sized chunks, a condition that is called memory fragmentation.
Unions and Structures are identical except for one very important aspect. Only one element in the union may have a value set at any given time.
A union is declared in the same way as a structure.
union int_or_float
Just like structures, the members of unions can be accessed with the . and → operators.

Functions

A function is a block of code that has a name and a property that it is reusable.
It can be executed from as many different points within a C Program.
The name of the function is unique in a C Program and it is Global.
The function either returns some value to the point it was called from or returns nothing.
Most functions contain the basic following formats:

  Functions with no arguments and no return values.
  Functions with arguments and no return values.
  Functions with arguments and return values.
  Functions that return multiple values.
  Functions with no arguments and return values.

Parameters (Pass by: Value, Address, Reference)

With pass by value, a copy of the actual value (the literal content) is passed.
When you use pass-by-value, the compiler copies the value of an argument in a calling function to a corresponding non-pointer or non-reference parameter in the called function definition. The parameter in the called function is initialized with the value of the passed argument. As long as the parameter has not been declared as constant, the value of the parameter can be changed, but the changes are only performed within the scope of the called function only; they have no effect on the value of the argument in the calling function.
When the function ends, the copy is destroyed.

Passing by address involves passing the address of the argument variable rather than the argument variable itself. Because the argument is an address, the function parameter must be a pointer. The function can then dereference the pointer to access or change the value being pointed to.

Passing by reference means that you don't pass the value of an object, you are passing the object itself. There are no copies made, only the original object is what is worked with.

Return Types
When a function completes its execution, it can return a single value to the calling program.
Usually this return value consists of an answer to the problem the function has solved.

Recursion
A function calling itself is called recursion, and normally you will have a conditional that would stop the recursion after a finite number of steps.
Recursion is most often used for jobs such as directory tree scans, seeking for the end of a linked list, parsing a tree structure in a database and factoring numbers.

/**
 ** An example calling a function passed by "value"
 **/
 
#include <stdio.h>
 
void func (int a, int b)
{
   a += b;
   printf("In func, a = %d    b = %d\n", a, b);
}
 
int main(void)
{
   int x = 4, y = 8;
   func(x, y);
   printf("In main, x = %d    y = %d\n", x, y);
   return 0;
}
/**
In the example, main passes func two values: 4 and 8.
The function func receives copies of these values and accesses them by the identifiers a and b.
The function func changes the value of a. 
When control passes back to main, the actual values of x and y are not changed.
The output is:
In func, a = 12 b = 8
In main, x = 4  y = 8
 **/
lab46:~/src/cprog$ nano
lab46:~/src/cprog$ gcc -o values values.c -lm
lab46:~/src/cprog$ ./values
In func, a = 12    b = 8
In main, x = 4    y = 8
lab46:~/src/cprog$

logic and operators (and, or, not, xor)

Logical operators are usually used with conditional statements.
A logical operator combines one or two conditions into a single new condition.
You can use the logical operators to test the truth value of two operands.
The operands can be expressions of a primitive type, or pointers.

      The boolean operators:
&& 		and
||		or
!		not

There are two kinds of AND operators in the C language: the logical AND, and the bitwise AND. The former is represented by the && operator, and the latter uses the & operator.

  ``&&'' (two ampersands) means AND \\ 
  For example:
     if ((x == 5) && (y == 10) && (z == 15))
     printf ("x is 5 and y is 10 and z is 15");

In the C language the logical OR uses the || operator, and the bitwise OR uses the | operator.

  ``||'' (two vertical bars) means OR
  For example:
       if ((x == 5) || (y == 10))
       printf ("x is 5 or y is 10");

The Boolean NOT operator, AKA logical NOT operator, is a unary prefix operator, which chages a Boolean true to false, and a Boolean false to true.

 
   ``!'' (an exclamation point) means NOT 

XOR stands for exclusive-or, it is a logical operand. XOR returns true if one and only one of the two arguments is true.
In C (and many other languages) the ^ is the character that represents XOR.

   K = I ^ J;

A xor example is as follows:
The result is false if both operands are false.
The result is true if either operand is true.
The boolean OR operation is also known as the logical OR operation.

  1 xor 0 = 1
  0 xor 1 = 1
  1 xor 1 = 0
  0 xor 0 = 0

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

When evaluating a conditional expression, expression 1 is evaluated first. If expression 1 is true, then expression 2 is evaluated etc.
Conditional expression frequently appear on the righthand side of a simple assignment statement. The resulting value of the conditional expression is assigned to the identifier on the left. The conditional operator has its own precedence, just above the assignment operator. The associativity is right-to-left. Decreasing order of precedence is as follows:

  1. - ++ - - ! 
  2. * / %
  3. + - ?:
  4. < <= > >=
  5. = = !=
  6. &&
  7. ! !
     ! !
  8. ?:
  9. = += -= *= /= %=

Array of char vs. C++ string data type [C++]

Arrays are useful because they can be used in many ways to store large amounts of data in a structured way.
C++ provides a structured data type called an array to store many values under the same name.
You can make an array out of any data-type including structures and classes.

  int array[100]; // This basic array, declares an array with 100 slots, or places to store values(also called elements). \\ 

To access a specific part element of the above array, you merely put the array name and, in brackets, an index number. This corresponds to a specific element of the array. The first index number, and thus the first element, is zero, and the last is the number of elements minus one. 0-99 in a 100 element array.
Character arrays are processed differently than you process other arrays. C++ provides a set of functions that can be used for C-string manipulation. The header file cstring describes these functions. Three of these functions are:
strcpy (string copy, to copy a C-string into a C-string variable—that is, assignment);
strcmp (string comparison, to compare C-strings);
strlen (string length, to find the length of a C-string). Aggregate operations are allowed for C-string input and output.
A string in C++ is an array whose base type is char. String variables can be declared just like other arrays:

 char phrase[14]; 

Multi-dimensional arrays have additional indices for each additional dimension. The index indicates the position of the individual component value within the collection of values. The index is also called the subscript.

  int array[SIZE][SIZE];

A multi-dimensional array can be initialized during declaration by equating the array to a listing of the array's members in brackets.
Multidimensional arrays are passed between functions just as single-dimensional arrays are. The parameter declaration in the function header looks like the original declaration of the variable and includes the index information. C++ requires that you specify the size of each index in a parameter array, except for the first. However, because leaving out the first index bound makes the declaration unsymmetrical, it is common to include the array bounds for each index in the declaration of a multidimensional array parameter.

Namespaces [C++]

A namespace defines a new scope. Members of a namespace are said to have namespace scope. They provide a way to avoid name collisions (of variables, types, classes or functions) without some of the restrictions imposed by the use of classes, and without the inconvenience of handling nested classes.
Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in “sub-scopes”, each one with its own name.

Defining a namespace is similar to defining a class. First goes the namespace keyword, followed by the identifier (the namespace name), followed by member declarations enclosed in braces. For example:

namespace direct 
{
  class compass
  {
  public:
    compass(int dir);
    void  setDirection(int dir);
  private:
    int   direction;
  }
 }

A namespace, however, cannot have access specifiers, such as public: or private:.
All members of a namespace are public. It cannot have a trailing semicolon, either.
An important difference between classes and namespaces, is that class definitions are said to be closed, meaning that, once defined, new members cannot be added to it.
A namespace definition is open, and can be split over several units.
There are four ways you can refer to namespace members:
The full member name, including the namespace it belongs to -

   std::cout << "Hello"; \\ 

Using-Declarations, as in -

   using std::cout;
   cout << "Hello";

Using-Directives, as in -

   using namespace std;
   cout << "Hello";     

Using aliases, as in -

   namespace w = X::Y; // This declares w as an alias for namespace X::Y, thus we can access Z using w::Z. \\      

Namespaces can be nested. One of the design goals of namespaces was to encourage programmers and vendors to wrap their libraries inside them, minimizing name collisions.

One additional thing that can be done with namespaces, is to use an unnamed namespace to avoid naming conflicts. To do so, simply declare a namespace with the normal syntax, but leave off the identifier.

      namespace
  {
     //functions
  }

When your program is compiled, the “un-named” namespace you created will be accessible within the file you created it in. In effect, it's as though an additional “using” clause was included implicitly. This effectively limits the scope of anything in the namespace to the file level (so you can't call the functions in that namespace from another other file). This is comparable to the effect of the static keyword.
You can also rename a namespace -

  namespace <new> = <old>

Type Casting Operators [C++]

Converting an expression of a given type into another type is known as type-casting.
Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type.
Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion.
Converting a derived-class reference or pointer to a base-class reference or pointer is called upcasting. It is always allowed for public inheritance without the need for an explicit type cast.
downcasting, the opposite of upcasting, is a process converting a base-class pointer or reference to a derived-class pointer or reference. It is now allowed without an explicit type cast.
The typeid operator can determine whether two objects are the same type.
The dynamic_cast operation and typeid operator in C++ are part of RTTI (Run-Time Type Information, or Run-Time Type Identification).
The C++ run-time type information permits performing safe typecasts and manipulate type information at run time.

Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.

  dynamic_cast <new_type> (expression)
  reinterpret_cast <new_type> (expression)
  static_cast <new_type> (expression)
  const_cast <new_type> (expression)

const_cast is typically used to cast away the constness of objects.
This type of casting manipulates the constness of an object, either to be set or to be removed.

reinterpret_cast is intended for low-level casts that yield implementation-dependent and it would not be portable.
reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked. It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.

static_cast can be used to force implicit conversions such as non-const object to const, or int to double. It can be also be used to perform the reverse of many conversions such as void* pointers to typed pointers, base pointers to derived pointers. But it cannot cast from const to non-const object.
static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type.
static_cast performs safe and relatively portable casts. For example, you use static_cast to explicitly document a cast that would otherwise take place automatically.

dynamic_cast is used to perform safe downcasting, i.e., to determine whether an object is of a particular type in an inheritance hierarchy.
dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.
dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.

Use static_cast for safe and rather portable casts, const_cast to remove or add only the const/volatile qualifiers of an object, and reinterpret_cast for low-level, unsafe and non-portable casts. Use dynamic_cast for conversions that must access the dynamic type of an object and RTTI capability-queries.

Implicit conversions do not require any operator:
short a=2000;
int b;
b=a;
Implicit conversions can also include constructor or operator conversions:
class A {};
class B { public: B (A a) {} };
A a;
B b=a;
Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion:
short a=2000;
int b;
b = (int) a;    // c-like cast notation
b = int (a);    // functional notation 

cprog Objective

Objective

Continuing to learn the syntax and operations needed for C Programming and also starting to learn the different syntax and code required in C++. Been working on the assigned topics which are a good way to learn new ways to write and utilize C code. Studying and working on Class structures and their implementation. Studying various print functions and what they do.

Method

I am writing new code in C and looking at code produced by others to improve my skills. Spending a lot of time reading the textbook and reading online. On my first solo project I worked on a Base Conversion program that converts a decimal number into other BASES, and now I'm working on program that will convert BINARY into decimal and OCTAL.

Measurement

As someone with no previous experience with C programming, I have started with the basics and I am working my way up the ladder with increasingly difficult programs and programming. I have assembled the BINARY to decimal program and right now I'm working on improving it. It does function, but not as well as I'd like.

lab46:~/src/cprog$ nano binary3.c
lab46:~/src/cprog$ gcc -o binary3 binary3.c -lm
lab46:~/src/cprog$ ./binary3
Binary to Decimal and OCTAL CONVERSION PROGRAM

You can convert a BINARY NUMBER into DECIMAL NUMBER

Enter a BINARY number that you want to convert to DECIMAL:
1111101

The BINARY number's equivalent in DECIMAL is:  125
Thanks for using the program

lab46:~/src/cprog$

Analysis

It takes a serious amount of work to make sure that you're using the correct procedures to get a program to run. Not only do you need the proper syntax and commands, but you need to know how to accomplish the task you are undertaking. The necessary functions required.
I've learned that I need to utilize the correct commands and syntax to get the program to run.
The program does finally compile and run, but I'm having some problems. I've had to change from a getch to a scanf.
I'm working on getting the OCTAL output besides the decimal output. Been getting error messages when compiling with the OCTAL output.
I've learned to use the Putty editor quite well and know most of the commands needed to get around on the program.
The books have quite a bit of information that has helped in ascertaining the correct procedures to use.
Matt's been very helpful whenever I've been stumped, (which is quite often).

Experiments

Experiment 1

Question

I am going to see if it's possible to take the project I just completed, the (Base Conversion Project), and restructure it so that it can be used to convert a binary number into a decimal number and an Octal number. The original program turned a decimal number into another base. I am going to attempt to see if I can make this new program with minimal changes to the original program. I will try and utilize as much of the other program as possible.

Resources

I've been collecting information and resources on the internet and from the text books available.
Gotten quite a bit of good information from the following web sites:
http://www.vectorsite.net/tscpp_1.html#m2
http://www.cprogramming.com/tutorial/base_systems.html
http://en.wikibooks.org/wiki/C_Programming/Print_version#Introduction
http://my-source-codes.blogspot.com/2010/08/c-program-binary-to-decimal.html
http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output

Hypothesis

I believe it may be possible by just changing the math functions and altering the input and output of the program. The original program will work as a guide to the new program. Since this is still a conversion program, it stands to reason that changing the formula should work. I have read that with a simple printf function that I can convert the decimal number that was converted to Octal.

Experiment

I will try to get the program to function converting the binary to decimal, then I will try adding an octal conversion to the program with minimal extra steps. I will copy the binary3.c program and edit it in Putty's editor and rename it binary2.c (which was an older version that didn't work properly).

Data

lab46:~/src/cprog$ nano binary3.c
lab46:~/src/cprog$ gcc -o binary3 binary3.c -lm
lab46:~/src/cprog$ ./binary3
Binary to Decimal and OCTAL CONVERSION PROGRAM

You can convert a BINARY NUMBER into DECIMAL NUMBER

Enter a BINARY number that you want to convert to DECIMAL:
1111101

The BINARY number's equivalent in DECIMAL is:  125
Thanks for using the program

lab46:~/src/cprog$
lab46:~/src/cprog$ nano binary3.c
lab46:~/src/cprog$ gcc -o binary2 binary2.c -lm
lab46:~/src/cprog$ ./binary2
Binary to Decimal and OCTAL CONVERSION PROGRAM

You can convert a BINARY NUMBER into DECIMAL NUMBER and Octal:

Enter a BINARY number that you want to convert to DECIMAL:
111101

The BINARY number's equivalent is :  DECIMAL :  61
                                     OCTAL :    75

Thanks for using the program

lab46:~/src/cprog$

Analysis

Based on the data collected:

Conclusions

Experiment 2

Question

Would like to make my Base Conversion program print out Binary numbers in groups of four to make them easier to read.

Resources

I'm collecting information and resources from the web and from the textbook to help me find the answer to my question.
Some of the sites I've visited so far are:
http://en.wikibooks.org/wiki/C_Programming/Print_version#Introduction
http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
http://einstein.drexel.edu/courses/Comp_Phys/General/C_basics/

Hypothesis

I hope to accomplish the task with just the printf function, but I may have set up the array correctly to make it work. I may have to get some help from MATT (again) if I can't figure this one out.

Experiment

My original output from the program appears as follows (notice that the binary number is in one long string):

lab46:~/src/cprog$ ./baseconvert
BASE CONVERSION PROGRAM
You can convert a POSITIVE whole DECIMAL NUMBER into another BASE

Enter the decimal number that you want to convert to another base:
The number must be a POSITIVE whole number greater than ZERO: 1477

Enter the BASE you'd like to convert the number to:
The BASE must be a POSITIVE whole number greater than ONE: 2

Decimal Number converted to the Base you chose is: 10111000101
Would you like to convert another number ?
ENTER 0 for YES, any other number to QUIT:1
Thanks for using the BASE CONVERSION PROGRAM

lab46:~/src/cprog$

Data

Continuing to work on the experiment to group the binary numbers into groups of four, such as: 1111 1010 1111 0111
I've been trying to use the printf with different specifiers to accomplish this task…so far, no luck. I've been able to print them at different widths and different lines, but not into groups of four YET.

Analysis

Based on the data collected:

Conclusions

What can you ascertain based on the experiment performed and data collected? Document your findings here; make a statement as to any discoveries you've made.