Rich Richardson - FALL 2011 SEMESTER Opus
C++
My name is Rich Richardson and I presently live in Watkins Glen. It's been quite a few decades since I've been in school. I started at Corning Community College back in January of 2011. I am enrolled in the Computer Science Program. This is my first attempt at an INTERNET ONLY class. I have been an avid computer user since my first exposure to a Commodore 64 back in 1982. I have a music recording studio in Interlaken, NY called Big Time Studio where many local and national artists have recorded. Presently, modern music studio's depend on computers to record and edit music. Big Time uses Avid's Pro Tools software for most of our recording needs. If you happen to be a musician, or have a band, and are interested in recording, or know someone else who is, let me know, and I'll give you more information.
Working on the RANGE project today. Acquainting myself with C syntax and entering code into the text editor on PUTTY. As an aid, feel free to use the following questions to help you generate content for your entries:
KEYWORDS:
STANDARD INPUT and OUTPUT STREAMS
stdin for (standard input),
stdout for (standard output),
stderr for (standard error).
stdio.h - standard buffered input/output, the I/O system:
#include <stdio.h>
stdin
File pointer for standard input stream. Automatically opened when program execution begins. Example - scanf("%d", &val);
stdout
File pointer for standard output stream. Automatically opened when program execution begins. Example - printf("Hello World");
stderr
File pointer for standard error stream. Automatically opened when program execution begins. Example - fprintf(stderr, "Can't open input file\n");
STANDARD INPUT is normally associated with the keyboard and STANDARD OUTPUT with the screen, unless redirection is used. STANDARD ERROR is where you display error messages. Standard error is normally associated with the same place as standard output; Redirecting standard output does not redirect standard error.
Header files define functions, constants and data types to use in your program, and are also used for declaring constants, data types and any other data that will be shared amongst multiple implementation files.
Using the #include <filename.h> format, such as:
#include <iostream>
#include <stdio.h>
#include <math.h>
In C, the usual convention is to give header files names that end with .h.
Here are some of the most common header files names and what they represent:
assert.h - Defines the assert() macro
ctype.h - Character handling
errno.h - Error reporting
limits.h - dependent limits
locale.h - Localization
math.h - math library
setjmp.h - Nonlocal jumps
signal.h - Signal handling
stdarg.h - Variable argument lists
stddef.h - Constants
stdio.h -I/O system
stdlib.h - Miscellaneous declarations
string.h - string functions
time.h -system time functions
Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations.
Types of operators available in C are as follows:
Arithmetic Assignment Logical/relational Bitwise
Arithmetic Operators
+ For performing Addition - For performing Subtraction / For performing Division * For performing Multiplication % Modulo for finding remainder in division operation -- Decrement (post and pre) ++ Increment (post and pre)
Assignment Operators
= *= Multiply /= Divide %= Modulus += Add -= Subtract )
Logical / Relational Operators
== Equal to != Not Equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to && Logical AND || Logical OR ! Logical NOT
Bitwise Operators
& AND | Inclusive OR ^ Exclusive OR << Shift Left >> Shift Right ~ One's compliment
int a = 6, b = -3, c = 2;
c= a - b * (a + c * 2) + a / 2 * b;
printf(“Value of c = %d \n”, c);
The command line is that it consists of a sequence of words, typically separated by whitespace.
Your main program can receive these words as an array of strings, one word per string.
The integer, argc is the argument count.
It is the number of arguments passed into the program from the command line, including the name of the program.
Command-line arguments are given after the name of a program in command-line operating systems.
#include <stdio.h>
int main ( int argc, char *argv[] )
Variables in C are memory locations that are given names and can be assigned values. Variables are used to store data in memory for later use.
There are 2 basic kinds of variables in C which are numeric and character.
Numeric variables can either be integer values or they can be Real values. Integer values are whole numbers without a fraction part or decimal point in them. Real numbers can have a decimal point in them.
Character variables are letters of the alphabet as well as all characters on the ASCII chart and even the numbers 0 - 9. Characters must always be put between single quotes. A number put between single quotes is not the same thing as a number without them.
To declare a variable, first put in the type of variable and then give the variable a name.
Variables should be declared at the top before any other commands are used.
The difference between signed and unsigned variables is that signed variables can be either negative or positive but unsigned variables can only be positive. By using an unsigned variable you can increase the maximum positive range.
When you declare a variable, it is automatically considered a signed variable unless you declare it as an unsigned variable, you may use the word signed if desired. To declare it as an unsigned variable you must put the word unsigned before your variable declaration.
int - Numeric - Integer (-32,768 to 32,767)
short - Numeric - Integer (-32,768 to 32,767)
long - Numeric - Integer (-2,147,483,648 to 2,147,483,647)
float - Numeric - Real 1.2 X 10-38 to 3.4 X 1038
double - Numeric - Real 2.2 X 10-308 to 1.8 X 10308
char - Character All ASCII characters
#include <stdio.h> int main() { unsigned int a; signed int b; return 0; }
Strings in C are represented by arrays of characters. String literals are words surrounded by double quotation marks.
Strings must have a 0 or null character after the last character to show where the string ends. The null character is not included in the string.
In a character array, create an array of chars and set each element in the array to a char value that makes up the string.
When sizing the string array you need to add plus one to the actual size of the string to make space for the null terminating character, “\0”
Declaring String
As in string definition, we have two ways to declare a string. The first way is, we declare an array of characters as follows:
For example, the following defines a string of 50 characters:
char name[50];
And in the second way, we declare a string as a pointer point to characters:
char* s = “string”;
Use %s when printing the string.
Opening & Closing Files
Opening a file is handled using the system function fopen().
The basic command used to open a file is:
FILE * fopen(char * filename, char * mode)
File-Access Modes
Normal Access
r Open existing file for reading
w Open file for writing, destroying the contents; create if necessary
a Append at end of file; create if necessary
Update Access (for fixed-length records)
r+ Open existing file for reading & writing
w+ Open file for reading and writing, destroying the contents
a+ Open file for reading & writing – all writing is appended to the end of the file
A pointer stores a reference to another value. A pointer is a memory address. Its location in memory is called its address.
Any direct assignment to a pointer variable will change the address in the variable, not the value at that address.
The assignment operation '=' between two pointers makes them point to the same pointee.
The “dereference” operation follows a pointer's reference to get the value of its pointee.
The dereference operator looks up the value that exists at that address.
A pointer type in C is the pointee type followed by a asterisk (*)
The asterisk (*) tells the compiler the variable is actually pointing to the data type and is not actually the data type.
Such as:
int* type: pointer to int
float* type: pointer to float
Typecasting is making a variable of one type, such as an int, act like another type, a char, in one single operation.
Put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable.
One use of typecasts is to force the correct type of mathematical operation to take place.
Typecasting is used in arithmetic operation to get correct result.
This is often needed in case of division when integer gets divided and the remainder is omitted.
float a; a=10/3; printf("%f\n",a);
In the above code, replacing the line a=10/3; with a=(float)10/3;
produces 3.33333 as the result because 10 is converted to a floating point value before the division. See below:
float a; a=(float)10/3 printf("%f\n",a);
Selection structures are used to change the flow of program execution.
It is achieved by establishing the truth or falsity of an expression (condition).
There are three basic types of selection structure that can be implemented
The if selection statement, if else selection statement and switch selection statement.
If is used when you want a single or a group of statements to be executed if the condition is true.
If the condition is false,
the statement is skipped and program continues by executing the first statement after the if selection structure.
It is possible to have if within an if statement. The if within an if statement is called nested if.
In the if else selection structure, the else statement will be executed when the condition is false.
In the switch statement, it allows you to select one from multiple options.
The switch selection structure consists of a series of a case label and an optional default case.
The switch statement works by comparing the value of the variable or expression within parentheses
with values specified in each case.
If there is a match, the statements following the case will be executed.
If there is no match, the default statement is executed.
At the end of each case,
the keyword break must be placed to exit from the switch immediately after statements execution.
Unlike the if statement, the switch case only executes outcomes when the variable matches one of the cases.
To execute a sequence of instructions repeatedly, while a condition is true, or until a condition becomes true,
is referred to as Iteration.
Repetition of statements with in program is referred to as a loop.
Looping in a program is the process of executing series of instructions repeatedly until a certain condition is met.
If statements can be nested within a loop.
Three types of repetition structure are the while loop, do while loop and for loop.
The while loop repeats of a set of instructions as long as the condition remains true.
When the condition becomes false,
the repetition terminates and the first statement after the repetition structure is executed.
The do while loop is similar to the while loop.
The do while tests the loop condition at the end of the loop structure or after the body of the loop is executed.
The do while loop is a compound statement that must be performed at least ONE TIME.
The while part of the condition statement is tested and if it is true,
it will go back up to the beginning and the body of the do while loop will be executed again.
This will continue until the while part of the condition is false.
The for statement handles all the details such as variable initialization,
variable update and loop condition within single parentheses.
The for loop loops from one number to another number and increases by a specified value each time.
The basic for statement includes:
for ( variable initialization; loop condition; variable update )
When using the for statement, programmers should be careful to choose a condition that is guaranteed to
terminate the loop at some point in time, or face the risk of incurring in a so-called infinite loop.
An array is a set of consecutive memory locations that are used to store the same types of data.
An array is a collection of similar elements.
These similar elements could be all integers or all floats or all characters.
Usually, an array of characters is called a “string”.
An array of integers or floats is called simply an array.
All elements of any given array must be of the same type.
Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.
Arrays must be declared before they can be used.
Example:
int myArray [5] = {1,2,3,4,5};
In C Language one can have arrays of any dimensions.
Typical two-dimensional array:
int ourArray [4] [2];
To define a pointer variable, do so by preceding its name with an asterisk.
Example:
int *ptr;
ptr is the name of the variable
The int means that we intend to use the pointer variable to store the address of an integer.
Learn to write programs using object-oriented problem solving concepts.
Writing a program in C, using structured and object-oriented problem solving concepts, and the use of standard libraries.
Follow your method and obtain a measurement. Document the results here.
Reflect upon your results of the measurement to ascertain your achievement of the particular course objective.
In the DATA TYPE EXPLORATION program to determine the values for “signed char” and “unsigned char”,
I want to see what the header “#include <math.h>” line does.
Also, what will happen if I don't include it in the program.
http://www.delorie.com/gnu/docs/glibc/libc_10.html
http://www.java2s.com/Code/C/Math/Howtousepow.htm
The resources listed have a definitions of how to use header files in C programming.
I don't believe the program will compile or function properly without the GNU C library header.
I believe that #include and the math.h file must be used.
I will try to compile and run the program without the header and see what happens.
I will take the range.c program and rename it range2.c without the header and try and see if it works.
Without the header the program will not compile, see below:
lab46:~/src/cprog$ gcc -o range2 range2.c -lm
range2.c: In function 'main':
range2.c:23: warning: incompatible implicit declaration of built-in function 'pow'
lab46:~/src/cprog$
BUT !!! the program will run OK…See below:
lab46:~/src/cprog$ ./range2
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values
A signed char is 1 bytes
The range of a signed char is -128 to 127
A signed char can store 256 unique values
lab46:~/src/cprog$
Based on the data collected:
Since this program ran without the header, I will have to run other programs without headers and compare the results.
I will try and find out what pow() is in the DATA TYPE EXPLORATION program and find out why am I multiplying by 8.
http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.7.html#pow
http://www.codecogs.com/reference/c/math.h/pow.php
http://www.java2s.com/Code/C/Math/Howtousepow.htm
The pow() function returns base raised to the exp power.
There's a domain error if base is zero and exp is less than or equal to zero.
Based on my last experiment, I don't believe the program will compile properly without the header #include <math.h>.
I believe that pow(2, (sizeof(sc)*8) must be used to get the proper value.
I will determine exactly what this math function does and how it operates, and why it needs to be multiplied by 8.
I will change the value of 'pow' and the 'sizeof' and see what happens.
I will take the range.c program and rename it range3.c and range4.c and see what the results are.
When using pow(4)and sizeof *8, here are the results:
lab46:~/src/cprog$ gcc -o range3 range3.c -lm
lab46:~/src/cprog$ ./range3
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values
A signed char is 1 bytes
The range of a signed char is 0 to -1
A signed char can store 65536 unique values
lab46:~/src/cprog$
As you can see the range of the signed char value has changed. The amount it can store has changed.
Originally the range was -128 to 127. The amount it can store was 256 unique values.
When using pow(2) and sizeof *6, here are the results:
lab46:~/src/cprog$ gcc -o range4 range4.c -lm
lab46:~/src/cprog$ ./range4
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values
A signed char is 1 bytes
The range of a signed char is -32 to 31
A signed char can store 64 unique values
lab46:~/src/cprog$
As you can see the range of the signed char value has changed. The amount it can store has changed.
Originally the range was -128 to 127. The amount it can store was 256 unique values.
Based on the data collected:
Since a signed char is 1 byte, 2^8 will give the correct 256 unique values a char can store.
I am wondering what the “\n\n” is doing at the end of each stanza's printf()in the DATA TYPE EXPLORATION program.
http://en.wikipedia.org/wiki/Newline
http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_056.htm
I know that \n calls for a new line. I believe that \n\n may call for 2 new lines.
I will take the range.c program and rename it range5.c without one of the \n's at the end of the printf() stanza.
I'll try more than 2 \n's at the end of the printf() stanza and see what happens in range6.c
With one \n you get the following:
lab46:~/src/cprog$ nano range5.c
lab46:~/src/cprog$ gcc -o range5 range5.c -lm
lab46:~/src/cprog$ ./range5
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values
A signed char is 1 bytes
The range of a signed char is -128 to 127
A signed char can store 256 unique values
lab46:~/src/cprog$
With 3 \n\n\n you get the following
lab46:~/src/cprog$ -o range6 range6.c -lm -bash: -o: command not found lab46:~/src/cprog$ gcc -o range6 range6.c -lm lab46:~/src/cprog$ ./range6 An unsigned char is 1 bytes The range of an unsigned char is 0 to 255 An unsigned char can store 256 unique values
A signed char is 1 bytes The range of a signed char is -128 to 127 A signed char can store 256 unique values
lab46:~/src/cprog$
Based on the data collected:
To get a newline you use the \n at the end of the stanza.
I am not sure if there is a more efficient way to make more newlines. I will explore other methods.
Working on Keywords today, including: Multi-Dimensional Arrays, Multi-file programs, Code stages (Source, Object, Binary) .
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
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
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; }
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$
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$
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$
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.
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$
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. = += -= *= /= %=
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.
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>
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
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.
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.
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$
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).
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.
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
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.
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).
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$
Based on the data collected:
Would like to make my Base Conversion program print out Binary numbers in groups of four to make them easier to read.
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/
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.
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$
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.
Based on the data collected:
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.
Continuing to work on Keywords today, including: Operator Overloading, Function Overloading, Classes and Objects, Const-Volatility Specifiers. Gathering information about different projects to complete.
Finishing work on Keywords today. Gathering additional examples and information about the keywords. Working on project today, gathering data necessary to complete the project.
The STL is a collection C++ libraries that allow you to use several well known kinds of data structures with out having to program them.
The Standard Template Library is a collection of classes that provide templated containers, algorithms, and iterators.
They are designed so that the code runs efficiently. The compiler does most of the work of generating the efficient implementations.
The STL includes the classes vector, list, deque, set, multiset, map, multimap, hash_set, hash_multiset, hash_map, and hash_multimap. Each of these classes is a template, and can be instantiated to contain any type of object.
Container class templates Sequence containers: vector Vector (class template ) deque Double ended queue (class template ) list List (class template )
Container adaptors: stack LIFO stack (class template ) queue FIFO queue (class template ) priority_queue Priority queue (class template)
Associative containers: set Set (class template ) multiset Multiple-key set (class template) map Map (class template ) multimap Multiple-key map (class template ) bitset Bitset (class template)
C++ provides two kinds of templates: class templates and function templates.
Templates allow functions and classes to operate with generic types.
This allows a function or class to work on many different data types without being rewritten for each one.
Declaration should start with the keyword template. A parameter should be included inside angular brackets.
The parameter inside the angular brackets, can be either the keyword class or typename. This is followed by the class body declaration with the member data and member functions.
One C++ Class Template can handle different types of parameters.
Templates reduce the effort on coding for different data types to a single set of code.
Testing and debugging efforts are reduced.
Compiler generates classes for only the used types.
If the template is instantiated for int type, compiler generates only an int version for the c++ template class.
template <class myType> myType GetMax (myType a, myType b) { return (a>b?a:b);
An abstract class is a class that is designed to be specifically used as a base class.
An abstract class contains at least one pure virtual function.
Declare a pure virtual function by using a pure specifier in the declaration of a virtual member function in the class declaration.
You can declare pointers and references to an abstract class.
You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit conversion, nor can you declare an object of an abstract class.
Not all methods in an Abstract Base Class must be pure virtual, some may have an implementation. This is especially true when creating a base class encapsulating a process common to a lot of objects.
An abstract class contains at least one pure virtual function.
You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.
The following is an example of an abstract class:
class AB { public: virtual void f() = 0; };
Exceptions provide a way to react to exceptional circumstances (like runtime errors) in program by transferring control to special functions called handlers.
To catch exceptions you must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.
An exception is thrown by using the throw keyword from inside the try block.
Exception handlers are declared with the keyword catch, which must be placed immediately after the try block.
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called exception and is defined in the <exception> header file under the namespace std. This class has default and copy constructors, operators and destructors, plus an additional virtual member function.
C++ provides three keywords to handle an exception.
Trying the normal flow:
To deal with the expected behavior of a program, use the try keyword as in the following syntax:
try {Behavior}
Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the program crash or instead of letting the compiler send the error to the operating system, you can transfer the flow of the program to another section that can deal with it. The syntax used by this section is:
catch(Argument) {WhatToDo}
Throwing an error: There are two main ways an abnormal program behavior is transferred from the try block to the catch clause. This transfer is actually carried by the throw keyword. Unlike the try and catch blocks, the throw keyword is independent of a formal syntax but still follows some rules.
You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention.
To overload the + operator for your class, you would provide a member-function named operator+ on your class.
The following set of operators is commonly overloaded for user-defined classes:
= (assignment operator) + - * (binary arithmetic operators) += -= *= (compound assignment operators) == != (comparison operators)
The assignment operator has a signature like the example below and the = operator takes a const-reference to the right hand side of the assignment:
In other words, assignment is right-associative. The last assignment operation is evaluated first, and is propagated leftward through the series of assignments.
class MyClass { public: ... MyClass & operator=(const MyClass &rhs); ... } MyClass a, b; ... b = a; // Same as b.operator=(a);
The number of operands to a function is fixed; that is, a binary operator takes two operands, a unary only one, and you can't change it. The same is true for the precedence of operators too; for example the multiplication operator is called before addition. There are some operators that need the first operand to be assignable, such as : operator=, operator(), operator[] and operator→, so their use is restricted just as member functions(non-static), they can't be overloaded globally.
C++ allows specification of more than one function of the same name in the same scope.
You overload a function name f by declaring more than one function with the name f in the same scope.
When you call an overloaded function named f, the correct function is selected by comparing the argument list of the function call with the parameter list of each of the overloaded candidate functions with the name f.
Overloaded functions enable programmers to supply different semantics for a function, depending on the types and number of arguments.
// overloaded function #include <iostream> using namespace std; int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; }
There two functions with the same name, operate, but one of them accepts two parameters of type int and the other one accepts them of type float. The compiler knows which one to call in each case by examining the types passed as arguments when the function is called.
A class can include a special function called constructor, which is automatically called whenever a new object of this class is created. This constructor function must have the same name as the class, and cannot have any return type; not even void.
Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution.
Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created.
The destructor fulfills the opposite functionality.
It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete.
A destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value.
The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated.
Classes are generally declared using the keyword class, with the following format: The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.
class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names;
An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire:
Private members of a class are accessible only from within other members of the same class or from their friends.
protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. Public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access.
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
class X { public: // Constructor for class X X(); // Destructor for class X ~X(); };
A destructor takes no arguments and has no return type. Its address cannot be taken.
A C++ compiler is a computer program that converts a C++ program from our form to a form the computer can read and execute. The computer works in binary which is a string of 1's and 0's thatcan be very quickly and accurately understood by the computer. The original C++ program is called the “source code”, and the resulting compiled code produced by the compiler is usually called an “object file”.
% gcc one.c -o one
This tells the compiler to run the preprocessor on one.c, compile it and then link it to create an executable called one. The -o option states that the next word on the line is the name of the binary executable file (program).
One or more object files are combined with predefined libraries by a linker, sometimes called a binder, to produce the final complete file that can be executed by the computer. A library is a collection of pre-compiled “object code” that provides operations that are done repeatedly by many computer programs.
Preprocessor directives are lines included in the code that are not program statements but directives for the preprocessor. These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor digests all these directives before any code is generated by the statements.
These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the preprocessor directive is considered to end. No semicolon (;) is expected at the end of a preprocessor directive. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash (\
When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++, it simply replaces any occurrence of identifier by replacement.
#define TABLE_SIZE 100 int table1[TABLE_SIZE]; int table2[TABLE_SIZE];
After the preprocessor has replaced TABLE_SIZE, the code becomes equivalent to:
int table1[100]; int table2[100];
A flag is a predefined bit or bit sequence that holds a binary value. Typically, a program uses a flag to remember something or to leave a sign for another program. For example, in a message being exchanged by two programs, a three-bit flag's field or data area might be set to different configurations:
001 (meaning “self-contained message”)
011 (meaning “one of several pieces of data in this message”)
111 (meaning “last piece of data in this message”)
An assembly language is a low-level programming language for computers, and it implements a symbolic representation of the machine codes and other constants needed to program a given CPU architecture.
A utility program called an assembler is used to translate assembly language statements into the target computer's machine code. It takes the assembly source code and produces an assembly listing with offsets. The assembler program takes each program statement in the source program and generates a corresponding bit stream or pattern (a series of 0's and 1's of a given length).
The assembler takes as its source code an assembly language program; this is a file of ASCII characters which is used to produce machine code.
Typically a modern assembler creates object code by translating assembly instruction mnemonics into opcodes, and by resolving symbolic names for memory locations and other entities.
In the earliest computers, programmers actually wrote programs in machine code, but assembler languages or instruction sets were soon developed to speed up programming. Today, assembler programming is used only where very efficient control over processor operations is needed. It requires knowledge of a particular computer's instruction set.
If a source file references library functions or functions defined in other source files the link editor combines these functions (with main()) to create an executable file.
Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker may find undefined functions (commonly, main itself). During compilation, if the compiler can not find the definition for a particular function, it would just assume that the function was defined in another file.
The job of the linker is to link together a bunch of object files (.o files) into a binary executable. This includes both the object files that the compiler created from your source code files as well as object files that have been pre-compiled for you and collected into library files.
Like the preprocessor, the linker is a separate program. Also like the preprocessor, the linker is invoked automatically for you when you use the compiler. The normal way of using the linker is as follows:
% gcc one.o two.o three.o -o myprogram
This line tells the compiler to link together three object files (one.o, two.o, and three.o) into a binary executable file named myprogram.
With C++, you can specify the level of access to member data and functions. There are three levels of access: public, protected, and private. The default access to class members (members of a class type declared using the class keyword) is private; the default access to struct and union members is public. For either case, the current access level can be changed using the public, private, or protected keyword.
The private keyword specifies that those members are accessible only from member functions and friends of the class. This applies to all members declared up to the next access specifier or the end of the class.
When preceding the name of a base class, the private keyword specifies that the public and protected members of the base class are private members of the derived class.
Default access of members in a class is private. Default access of members in a structure or union is public.
Default access of a base class is private for classes and public for structures. Unions cannot have base classes.
private: [member-list] private base-class
The protected keyword specifies access to class members in the member-list up to the next access specifier (public or private) or the end of the class definition. Class members declared as protected can be used only by the following:
Member functions of the class that originally declared these members.
Friends of the class that originally declared these members.
Classes derived with public or protected access from the class that originally declared these members.
Direct privately derived classes that also have private access to protected members.
When preceding the name of a base class, the protected keyword specifies that the public and protected members of the base class are protected members of its derived classes.
Protected members are not as private as private members, which are accessible only to members of the class in which they are declared, but they are not as public as public members, which are accessible in any function.
Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.
protected: [member-list] protected base-class
When preceding a list of class members, the public keyword specifies that those members are accessible from any function. This applies to all members declared up to the next access specifier or the end of the class.
When preceding the name of a base class, the public keyword specifies that the public and protected members of the base class are public and protected members, respectively, of the derived class.
Default access of members in a class is private. Default access of members in a structure or union is public.
Default access of a base class is private for classes and public for structures. Unions cannot have base classes.
public: [member-list] public base-class
Friends are functions or classes declared with the friend keyword.
A class grants access privileges to its friends. Normally a developer has technical control over both the friend and member functions of a class (else you may need to get permission from the owner of the other pieces when you want to update your own class).
You can declare friend functions or friend classes to access not only public members but also protected and private class members.
friend class aClass;
Friend declarations can go in either the public, private, or protected section of a class–it doesn't matter where they appear. In particular, specifying a friend in the section marked protected doesn't prevent the friend from also accessing private fields
class Converter { private: int data; int bass; // ... friend class Binary; // class Binary can now access data directly };
Scope refers to identifiers, that is types, functions, classes and variables and is that part of the source code where the particular identifier is visible.
Variables have a finite life-time a program executes. The scope of an object or variable is simply that part of a program in which the variable name exists or is visible to the compiler.
A variable’s scope determines who can see the variable, and how long it lives for. Variables declared inside a block are called local variables, and local variables have block scope (also called local scope). Variables with block scope can be accessed only within the block that they are declared in, and are destroyed as soon as the block ends.
Because each function has it’s own block, variables in one function can not be seen from another function.
Blocks allow multiple statements to be used wherever a single statement can normally be used.
Local scope is activated when the flow of the program enters it, and deactivated when it leaves it. Objects in local scope are constructed whenever their definition is encountered, and destroyed when the scope is exited. Such objects are also called automatic (because they are automatically created and destroyed), or stack objects (because they occupy memory that is allocated on the program's stack).
Local scopes are usually, but not always, delimited by the curly braces.
The default scope is defined as global scope, this is commonly used to define and use global variables or other global constructs (classes, structure, functions, etc), this makes them valid and visible to the compiler at all times. It is considered a good practice to use a namespace scope for hiding the otherwise global elements, without removing their validity.
Global is usually outside of the curly braces.
In C++, a declaration of an object at file scope is just a declaration (and not also a definition) if and only if it
has an explicit extern keyword specifier and no initializer.
Each object declared at file scope must be defined exactly once. All but one declaration must have both an explicit
extern keyword specifier and no initializer.
Any name declared outside all blocks or classes has file scope. It is accessible anywhere in the translation unit after its declaration. Names with file scope that do not declare static objects are often called global names.
In C++, file scope is also known as namespace scope.
lab46:~$ cd src lab46:~/src$ gcc -o hello hello.c lab46:~/src$ ./hello Hello, World! lab46:~/src$
I've been bpending 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 a simple C++ program that will convert miles to kilometers. I'm also working on a small program using VECTORS.
I have been continuing to learn the syntax and operations needed for C++ Programming. Been working on the assigned keywords and topics which are a good way to learn new ways to write and utilize the C++ code.
After spending many hours, weeks on the miles conversion program and ironing out all the kinks, I've gotten it to compile properly and run without errors.
Reflect upon your results of the measurement to ascertain your achievement of the particular course objective.
What is the question you'd like to pose for experimentation? State it here.
Collect information and resources (such as URLs of web resources), and comment on knowledge obtained that you think will provide useful background information to aid in performing the experiment.
Based on what you've read with respect to your original posed question, what do you think will be the result of your experiment (ie an educated guess based on the facts known). This is done before actually performing the experiment.
State your rationale.
How are you going to test your hypothesis? What is the structure of your experiment?
Perform your experiment, and collect/document the results here.
Based on the data collected:
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.
What is the question you'd like to pose for experimentation? State it here.
Collect information and resources (such as URLs of web resources), and comment on knowledge obtained that you think will provide useful background information to aid in performing the experiment.
Based on what you've read with respect to your original posed question, what do you think will be the result of your experiment (ie an educated guess based on the facts known). This is done before actually performing the experiment.
State your rationale.
How are you going to test your hypothesis? What is the structure of your experiment?
Perform your experiment, and collect/document the results here.
Based on the data collected:
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.
If you're doing an experiment instead of a retest, delete this section.
If you've opted to test the experiment of someone else, delete the experiment section and steps above; perform the following steps:
Whose existing experiment are you going to retest? Prove the URL, note the author, and restate their question.
Evaluate their resources and commentary. Answer the following questions:
State their experiment's hypothesis. Answer the following questions:
Follow the steps given to recreate the original experiment. Answer the following questions:
Publish the data you have gained from your performing of the experiment here.
Answer the following:
Answer the following: