User Tools

Site Tools


notes:cprog:cprog-fall2014

C/C++ Programming Course Notes

09/02/2014

Class Notes Project (this) author - provides content designer - provides stylistic tweaks, DocuWiki syntax reviewer - provides recommendations to content and style

Access Lab46 mail using alpine(e-mail system) will be implementing a points system for doing some ambiguous task of awesomeness or something to that effect per week and drawing a persons name to earn the point for that week?

Variables

73 integer 3.14 float 'c' character “hello” array of characters (or a “string”) “\n” special characters (in this case a newline“

“hello\0” - the '\0' is an ASCII null terminator that ends a string in C

single quotes are used for a single character, more than a single character and double quotes(”“) are used.

0xdeadbeef memory address (usually in hexadecimal)

your user name in Unix is stored in the variable $USER

To Make a Variable

  • declaration of variable
  • initialization of variable

declaring variables: type name; declaring and initializing in one line: type name = 0;

Data types of Variables

int - integer

char - character

math style: x+2=y

computer style - variable goes to the left, isolated: y=x+2

'*' - reference pointer

'&' - address of a pointer

'0x…' is assumed to be hexadecimal

'0…' is assumed to be an octal value

Memory Address Table

0 1 2 3
0 5 (a)
1 073 (c)
2
3 0x12 (d)

in class source code for data types and variables, var1.c:

1
#include<stdio.h>
 
int main()
{
    int a = 5;
    int b = 0x3D, c = 073;
    int *d;
    char e, *f;
    e = 'X';
    d = &c;
    f = &e;
 
    printf("address of a is : %p\n",&a);
    printf("address of b is : %p\n",&b);
    printf("address of c is : %p\n",&c);
    printf("address of d is : %p\n",&d);
    printf("address of e is : %p\n",&e);
    printf("address of f is : %p\n",&f);
 
    printf("a contains: %d\n", a);
    printf("b contains: %d\n", b);
    printf("c contains: %d\n", c);
    printf("d contains: 0x%x\n", d);
    printf("e contains: %c\n", e);
    printf("f contains: 0x%hhX\n", f);
 
    printf("d dereferenced is: %d\n", *d);
    printf("f dereferenced is: %c\n", *f);
 
    return (0);    
}

This is compiled with:

gcc var1.c -o var1

or

gcc -o var1 var1.c

as long as the source code file (var1.c)isn't directly after the -o flag.

program is run with:

./var1

my output: (which may be extraneous)

address of a is : 0x7ffffa714a1c
address of b is : 0x7ffffa714a18
address of c is : 0x7ffffa714a14
address of d is : 0x7ffffa714a08
address of e is : 0x7ffffa714a07
address of f is : 0x7ffffa7149f8
a contains: 5
b contains: 61
c contains: 59
d contains: 0xfa714a14
e contains: X
f contains: 0x7
d dereferenced is: 59
f dereferenced is: X

End Notes - Tuesday September 02, 2014 - MJP

Author - Matthew Page

(Note to guys following me, I'm putting up the content and resisting my OCD-like urge to format the text in some way to leave something for you guys to do, with one exception, I am throwing the code tags around today's source code as I already referenced ahead of time to another student that I would be writing this up tonight and that what I'm writing up does in fact compile and work as desired. -MJP 09/02/2014) Note 2 As of 9:00 PM 09/02/2014 I am officially done putting in MY content and pass the baton early if the guys below me wish to run with it now. Also if you need to contact me for anything I'm “notmatt” on the IRC, feel free to point out my shortcomings. :) -MJP)

Designer - Dan Shadeck

Created headlines for sections of the notes. Used the ordered list item for “To Make a Variable”. Source code and cli tags were completed before my editing :(

Reviewer - Mike Merrick

Simple spelling corrections. Great and useful tips and help in these notes for everyone

Master of the known universe (and beyond) - Matthew Haas

Beautiful job all around- this should serve as an excellent example for future note taking sessions. I made 3 quick changes–

  1. in the memory table, address 0x00, you had “int a”… shouldn't this be 5? I made that change.
  2. if you noticed the c variable in the memory table above was rendering as a copyright symbol '©', I enclosed it in a set of nowiki tags to prevent this.
  3. I added the language to the code tag, as well as line numbers. View the section source to see how this is done. You'll notice that identifying the language will enable color coding.

But as I said: excellent work, one and all.

09/04/2014

Var1.c

1
#include<stdio.h>
int main()
{
     int a=5;
     int b=0x3D, c=073;
     int *d;
     char e, *f;
     e = 'X';
     d=&c;
     f=&e;
 
     printf("address of a is : %p\n",&a);
     printf("address of b is : %p\n",&b);
     printf("address of c is : %p\n",&c);
     printf("address of d is : %p\n",&d);
     printf("address of e is : %p\n",&e);
     printf("address of f is : %p\n",&f);
 
     printf("a contains: %d\n", a);
     printf("b contains: %d\n", b);
     printf("c contains: %d\n", c);
     printf("d contains: %p\n", d);
     printf("e contains: '%c'(%hhd)\n", e, e);
     printf("f contains: %p\n", f);
 
     printf("d dereferenced is: %d\n", *d);
     printf("f dereferenced is: '%c'(%hhd)\n", *f, *f);
 
	return (0);
}

If we look at the var1.c we notice that a, b, c, d, e, and f are all variables available in the main() code block. This is an example of variable scope. Anything that is declared outside of the main() code block would be called global or file scope. With in our main() code block we can also have sub-blocks of code. This is called sub-scope.

Scope

Below is a representation of global, block, and sub-scope.

1
/* Ex: Global Scope */
int c;
{     
    /*Ex: Block Scope */
    int a;
        {
        /*Ex: Sub-Scope */
            int b;
        }
}    

Variable Declaration and Initialization

Declaration and initialization of variables can be done all in one or as two separate things.

  • declaration: int a;
  • initialization: a=5;
  • both: int a=5;

This small piece of Var1.c is a good example of this!

1
     int a=5;
     int b=0x3D, c=073;
     int *d;
     char e, *f;
     e = 'X';
     d=&c;
     f=&e;

Looking at line 4 & 5 in the above code also demonstrates the use pointers and characters.

Char e, *f; is the declaration e = 'X'; is the initialization

*I'm going to need some help on the pointer portion of this :/*

Pointers Cont.

To Define a pointer variable proceed with its name in asterisk. I.E.

int *ptr;  // The '*' informs the compiler that we want
           // a pointer variable to set aside said allotment 
           // of bytes in memory.
 
int j, k; 
 
k = 2; 
j = 7;    <-- line 1 
k = j;    <-- line 2 

In the above, the compiler interprets the j in line 1 as the address of the variable j (its lvalue) and creates code to copy the value 7 to that address. In line 2, however, the j is interpreted as its rvalue (since it is on the right hand side of the assignment operator '='). That is, here the j refers to the value stored at the memory location set aside for j, in this case 7. So, the 7 is copied to the address designated by the lvalue of k.

ptr + 1; would be a memory allocation of 4 decimal. using the unary ++ operator, either pre- or post-, increments the address it stores by the amount sizeof(type) where “type” is the type of the object pointed to. 4 for an integer

References for Chapter 1

“The C Programming Language” 2nd Edition B. Kernighan and D. Ritchie Prentice Hall ISBN 0-13-110362-8

Format Specifiers

”%p“ substitutes a memory address.

We cannot know the actual address of variable as it changes everytime we run the program, so we reference the address of the variable.

a,b,c are integers
”%d“ - a format specifier, ”%d“ is used for integers.
”%d“ is for signed integers.
”%u“ is for unsigned integers.

”%x/%X“ hexidecimal values.

”%c“ displays it as an ASCII character http://www.asciitable.com American Standard Code for Information Interchange.
7-bit/8-bit ASCII 16-bit Unicode (first 8 bytes are ASCII) other ones, IBM-EBCDIC

e = 'A';
same as:
e = 65;

4 bytes - integer
2 bytes - ”%hd“ - half signed int (cuts range and size in half)
1 byte - ”%hdd“ - half half signed int(cuts range and size in half, then cuts both in half again.)

All chars need to be placed in between single quotes as displayed above.

This is compiled with:

gcc var1.c -o var1

or

gcc -o var1 var1.c

as long as the source code file (var1.c)isn't directly after the -o flag.

program is run with:

./var1

Author Note: Matt I was going to add the portion about compiling var1.c and running it but doing this with out styling is going to kill me. Do you want to add this portion from what you already made? If this is an issue just shoot me an email dshadeck@corning-cc.edu.

Designer Note: Added the compile and run section, as well as format specifiers section. Sadly, much of the formatting was done before I got here. :( I fully understand not putting in some things unformatted as they would have drove me crazy too to leave them in such a state. If you or the reviewer (I forgot who got that spot) have any issues or need to consult with me, I can be emailed at me@matthewjpage.com MJP 09/06/2014

Reviewer: That would be me Jgates1 My email with any questions Jacques2826@gmail.com, added a couple things about pointers and a reference to some more info nothing like waiting till the last minute 09/07/2014

09/09/2014

status

First I would like to remind everybody of this useful command that is now available to us:

lab46:~$ status cprog

This will display your progress on attendance, opus, and projects.

scanf

Today we were introduced to a new function called scanf. To prompt users for something to scan you must leave the \n new line identifier out. Then continue on to the scanf function. In the first perimeter type the data type you intend to scan. for example, you would type %d for an integer.

Scanf changes something and put it in some address.

In the next perimeter you would use the & operator to assign the scanned info to a variable. We used this function to create a nifty program that calculates averages.

1
#include <stdio.h>
main()
{
    int a;
    int b;
    int c;
    int d;
    float avg;
 
    printf("Enter score 1: ");
    scanf("%d",&a);
    printf("Enter score 2: ");
    scanf("%d",&b);
    printf("Enter score 3: ");
    scanf("%d",&c);
    printf("Enter score 4: ");
    scanf("%d",&d);
 
    avg=(float)(a+b+c+d)/4;
 
    printf("The average of %6.4d,%d,%d,%,d is %.2f\n",a,b,c,d,avg);
 
    return(0);
}

side notes

  • (float) is declared during the math equation to get the modulus.
  • In the last printf the first integer and the answer's integer are both multiplied by floating point numbers for precision and padding.

Author & Designer: Derek Southard. Just a reminder to do HG Pull then HG Push at each class and lab. Reviewer: Sudesh Tiwari.

09/11/2014

Today in class we went over addressing multiple variables without having to write a statement for each individual variable being entered in.

#include<stdio.h>
 
int main()
{
        int number[2];
        int i; input;
        number[0]=0;
        number[1]=0;
 
        printf("how much to count?");
        scanf("%d",&input);
        for(i=o;i<input;i=i+1)
		{
			number[1]= number[1]+1;
			if(number[1]>9)
 
        }
 

Average program with an array

1
#include <stdio.h>
 
int main()
{
	float avg = 0;
	int score[4], count = 0;
	for(count = 0; count < 4; count = count +1)
	{
			printf("enter score %d: ",(count + 1));    //math!
			scanf("%d", &score[count]);
			avg = avg + score[count];
	}
	avg = avg/count;
	printf("The average is: %.2f\n",avg);
	return(0);
}
/* or int score[]={73,86,99,92};
for is a loop like a while */

Format String Specifiers

Variable type Length Modifier Example

short int, unsigned short int h short int i = 3; printf( ”%hd“, i ); long int or unsigned long int l long int i = 3; printf( ”%ld“, i ); wide characters or strings l wchar_t* wide_str = L”Wide String“; printf( ”%ls“, wide_str ); long double L long double d = 3.1415926535; printf( ”%Lg“, d );

You can print all of the normal C types with printf by using different placeholders: int (integer values) uses %d float (floating point values) uses %f char (single character values) uses %c character strings (arrays of characters, discussed later) use %s

Author Jacques Gates

Designer Michael Merrick

Reviewer: Derek Southard. Made some minor spelling changes and added the average program with the array.

09/16/2014

Today we took the program we wrote on 09/14/2014 and reworked it to count in different base numbers.

1
#include <stdio.h>
#define MAX 2 // When ever the computer sees MAX it counts it as 2.
 
int main()
{
        int base,i,input,number[MAX]; // calling our integers.
        for(i=0;i<MAX;i++) // sets i=0 and when MAX is larger than i the program continues from here.
        {
                number[i]=0;
        }
        printf("What base?(2-10): "); // calling our base number and how much you want to count.
        scanf("%d",&base);
        printf("How much to count? ");
        scanf("%d",&input);
        for(i=0;i<input;i++)// when i is less than your input the program runs from here.
        {
                printf("%d %d\n",number[0],number[1]); //prints the current value of number[0] and number[1].
                number[MAX-1]=number[MAX-1]+1;
                if(number[MAX-1]>(base-1))
                {
                        number[MAX-1]=0;// when MAX-1 reaches the base number set it = 0
                        number[MAX-2]++;// when MAX-1 reaches the base number add 1 to MAX-2.
                }
        }
        return(0);
}

increment of a variable ( up or down 1) use

++i; up +i; down

MAX 2 is a variable used to do different functions in the same program. Changing the number after MAX allows you to change parameters in the program MAX at 2 the numbers will be 0,1 and the program will run 2 times.

With this we are able to count in bases from 2-10. We were also asked to attempt making it count to three digits then four before the next class.

We also discussed a couple of math tricks like 25². add 1 to the first number and then multiply for this it would 2+1=3 3*2= 6 for 5 5*5=25 hence you only being able to do numbers ending in 5

For multiplication of eleven, take the two end numbers and place them on the sides then add the numbers together for the middle so it would look like 32 *11 352

This lead into a take home project where we have to write a program that solves squares of 5 through this style.

Author-David Woodcock (Sorry it took so long to upload I was very busy the past 2 days)

Designer Jacques Gates made a couple spelling corrections and corrected the math tips./ tricks, definition of MAX

Reviewer- Zack Golden made some spelling/grammar corrections. All material from class was present and organized/designed in a clearly for easy reading.

09/18/2014

Today in class we went over our base counter program. We saw that whenever we took our program to the next digit there was a pattern. For example, 2 digit has MAX-1, 3 digit MAX-1 and MAX-2, and 4 Digit has MAX-1,MAX-2, and MAX-3. We see from the pattern that a MAX function keeps getting added with the previous function. Matt then introduced to us using loops inside loops causing out brains to go berserk.

1
#include <stdio.h>
#define MAX     6
 
int main()
{
        int base, i, input, j, number[MAX];
 
        for(i = 0; i < MAX; i++)
        {
                number[i] = 0;
        }
 
        printf("What base? (2-10): ");
        scanf("%d", &base);
 
        printf("How much to count? ");
        scanf("%d", &input);
 
        for(i = 0; i < input; i++)
        {
                for (j = 0; j < MAX; j++)
                        printf("%d ", number[j]);
                printf("\n");
 
                number[MAX-1] = number[MAX-1] + 1;
 
                for (j = 1; j < MAX; j++)
                {
                        if (number[MAX-j] > (base-1))
                        {
                                number[MAX-j] = 0;
                                number[MAX-(j+1)] = number[MAX-(j+1)] + 1;
                        }
                }
        }
        return(0);
}

Just a reminder that our assignment called “squares” dealing with making a program that squares numbers ending in 5 is due this coming week.

Author- Zack Golden designer - Sudesh Tiwari reviewer - Dan Shadeck

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

09/23/2014

New Project announced - Day of the Week

a programmatic solution to a mental math trick to determine the day of the week that January 1st of a given year willf all on, by associating a number with each day of the week as:

Sunday Monday Tuesday Wednesday Thursday Friday Saturday
0 1 2 3 4 5 6
  • Note: We are now on our next cprog project called Day of Week. You can find this on the project page.

this is the safe way to determine sizes instead of hard coding, as for example, a 32 bit system and a 64 bit system would have diffent sizes:

sizeof(long int)*6

DataType Sizes

1
#include <stdio.h>
 
int main()
{
    printf("A char is %ld bytes.\n", sizeof(char));
    printf("A short int is %ld bytes.\n", sizeof(short int));
    printf("A int is %ld bytes.\n", sizeof(int));
    printf("A long int is %ld bytes.\n", sizeof(long int));
    printf("A long long in is %ld bytes.\n", sizeof(long long int));
 
    return(0);
}
 
    // The sizeof funtion outputs the size of any data type. 
  //If you want to know the size of datatype in long ints use %ld (this is the safe way to 
  //do it if you have a newer compiler. Therefore, this program prints the size of a char, 
 //short int, int, and long int. This is from smallest to biggest; although, 
  //an int and long int are of the same size.

Author - Mike Merrick
Designer - Derek Southard - note to author: Aren't these the 9/23 notes from unix? I will put up the new 9/23 code we did (in cprog) + tag and explain it it.
Note to reveiwer: Add anything you think I may have missed. Also, you may want to delete the top portion of the notes.

(Thank you for fixing my mistake)mmerrick

Reviewer - Matthew Page - added a header for this day 09/23/2014, added a little bit up top

09/25/2014

 LAIR board 09/25/2014

Datatype cont'd Sizeof( ) signed or unsigned

  1. char
  2. short int
  3. long int
  4. long long int

3 bit = 2^3 = 8 possible combinations

	Unsigned	Signed
000	0	+0
001	1	+1
010	2	+2
011	3	+3
100	4	-4
101	5	-3
110	6	-2
111	7	-1

Is most significant bit 0=positive 1=negative

Two complement -inverting the first number and adding one

100	101	110	111
010	010	001	000
+1	+1	+1	+1
-100	= -011	= -010	= -001

0000 0000 1111 1111 256 unique values • Unsigned char • (0-255) • (Signed char) • (-128 - +127)

FFFF 1111 1111 1111 1111 —– 16 bits +127 is the maximum signed value

LOGIC in C
& - bitwise AND
| - bitwise OR
^ - bitwise XOR

Examples of AND and OR

AND

AB	X
00	0 
01	0
10	0
11	1

OR

AB	X
00	0
01	1
10	1
11	1

Author - Sudesh Tiwari Editor - David Woodcock - I was busy with two other projects from another class this week I am going have to leave this up to the reviewer if he wants. Reviewer - Matthew Page - added my pic of the board from class today, fixed LOGIC section with nowiki tags. Still have to clean this up a little.

09/30/2014

Makefile

  • collection of actions instructing Make how to perform the task.
  • “make help” to bring up actions
  • use “make” to make things

CMD arguements

  • argc- argument counter (at least one)
  • argv- argument vector, an array of strings
  • first argument must be int, second must be char

Program

  • CLA.c
1
#include<stdio.h>
 
int main(int argc, char **argv)
{
        int i;
        printf("You called %s with %d arguements\n", argv[0], argc-1);
        printf("Arguement breakdown as follows: \n");
        for(i=0;i<argc;i++)
                printf("argv[%d]: %s\n",i,argv[i]);
 
        return(0);
}

Pipe Math assignment

  • running/creating one of each program (numbers, maths, bases)
  • scan for input but doesn't have to be user guided
  • coverts ascii to number using atoi(3), value=atoi(argv[1]);
  • cd pipemath to access files

Author- Zack Golden, you can email me at justgolden07@gmail.com if you have questions or suggestions.

##### OCT 2 2014######## OCT 2 2014

if (a==1) {

} if(a==2) {

}

vs

if(a==1) { || } else if (a==2) {

}

if statements work code code code compare a,1 begin part 2014 code code code

fetch decode execute store

all program in memory

crafty people came up with

fetch decode encode store (Four stage pipeline)

Key POINT USE IF AND IF ELSE STATEMENTS

loops and whiles are expensive in the pipeline

new code: readability = less efficient vs writable=more efficient

readability tool modularity subroutine procedure Function

IE: y=F(atoi(argv[1]));

how to write a function: variable= name give to a regain of memory that conforms to a cretin type of data

declare the variable	
define/ initiation

functions

declare	
define

functions are made global most of the time because they are used troughs the program
to make global make outside of main

(Parameters)

#include <stdio.h> #include <stdlib.h>

int sum(int *arr, int n);<------- function prototype
float average(int,int) return type 

10/02/2014

10/07/2014

10/09/2014

10/21/2014

10/30/2014 Knowledge Assessment during class time

Topics include variables, functions and function calls if statements, Binary.

Use the 'grabit' to get a file”Sumavghighlow.c“ Reviewed the file. Discussed Library and header files. <stdio.h> <stdlib.h>

Declared global function. A function that can be called anywhere in the program. int sum(int *, int); float average(int, int);

int main() This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name. Declared local function.

10/23/2014


USEFUL FUNCTIONS

  • malloc - which stands for “memory-allocation” can be used to allocate specified amounts of memory.
  • sizeof - function that returns the size of a specified datatype.
    EXAMPLE (goes with our funcfun program.)

    1
    scores=(int*)malloc(sizeof(int)*num); 
    /*size of returns thesize of an int and multiply's it by 
    the number of ints aka num,(num=4 in this case), then 
    malloc allocates the specified amount of memory. In this 
    case, it will take 4 bytes times 4 bytes giving 16 bytes, 
    which is just enough to store 4 integers.*/ 
    *(scores+0) 
    /*dereferences what's at the scores address and if you add 
    you can dereference the things at the address shifted up 
    from the starting adress.*/


DATA STRUCTURES

  • The WIKIPEDIA Definition
  • A node is another word for a structure, they can be used together: structure node.
  • A structure pointer looks like this →, instead of this *.
    MATT'S STRUCTS CODE

    1
    /*
     * structs.c
     *
     *  An example of using structs in C, along with arrays.
     *
     * To compile: gcc -o structs1 structs1.c
     *
     */
    #include<stdio.h>
    //#include<string.h>
     
    int main()
    {
    	int i;
    	char entry[80], entries = 4, junk;
     
    	struct person {
    		char name[80];
    		int age;
    		float height;
    	};
     
    	do {
    		printf("How many people in your database? ");
    		scanf("%d", &entries);
    	} while (entries <= 0);
     
    	struct person people[entries];
     
    	for(i=0; i<entries; i++)
    	{
    		printf("Person %d of %d:\n", (i+1), entries);
    		printf("==============\n");
     
    		// prompt for name (string)
    		printf("Please enter the person's first name: ");
     
    		scanf("%s", people[i].name);
    //		fgets(entry, sizeof(entry), stdin);
    //		strcpy(people[i].name, entry);
     
    		// prompt for age (integer)
    		printf("Please enter %s's age: ", people[i].name);
    		scanf("%d", &people[i].age);
     
    		// prompt for height (float)
    		printf("Please enter %s's height: ", people[i].name);
    		scanf("%f", &people[i].height);
     
    		// Get newline out of the input stream
    		junk = fgetc(stdin);
    //		fgets(junk, sizeof(junk), stdin);
    	}
     
    	printf("\n\nThe names of the people are:\n");
    	for(i=0; i<entries; i++)
    	{
    		printf("#%d: %s\t", (i+1), people[i].name);
    	}
    	printf("\n\n");
     
    	printf("The full bios of the people are:\n");
    	for(i=0; i<entries; i++)
    	{
    		printf("#%d: %s, age: %d, height: %f\n", (i+1), people[i].name, people[i].age, people[i].height);
    	}
     
    	return(0);
    }


Author, Designer, & Reviewer
Derek Southard 2014/10/24 20:39

10-28-2014

Knowledge Assessment 31 Oct 2014 REVIEW Interacting with files inside the file system

  1. fundamental actions to files
    1. Open
    2. Read
    3. Write
    4. Append
    5. create
    6. remove/delete
    7. Seek/Search

Lets Explore some of these features (datafile.txt)

how to interact with files is File *fprt; fopen=to open a file they return a FILE * ( file pointer)

When you append it goes to the last spot in the file so you dont loose your data F seek=scroll keys in the file the computer thinks on a 1D stystle with the idea of everything being on one line

When ever you use fpfrintf three file pointers are auto created
-file Stdin, stdout,stdir

Example of the Code:

1
#include <stdio.h>
#include <stdlib.h>
 
int main()
 
{
        char c;
        int i;
        int count=0;
        FILE *fptr;
        fptr=fopen("datafile.txt", "r");
 
 
        if(fptr==NULL)
 
        {
                fprintf(stdout, "Error Opening file!\n");
                exit(1);
 
        }
        //for(i=0;i<5;i++)
        //while(c!=EOF)
        while((c=fgetc(fptr))!=EOF)
        {
 
                //c=fgetc(fptr);
                fprintf(stdout,"i just read a '%c'\n",c);
        }
        fclose(fptr);
 
        return(0);
}

Author/Reviewer=Michael Merrick

11-04-2014

We started C++ today (C++ programming is 90% similar to C) Object Oriented programming C++

Three major points of Object Oriented Programming:

  • Polymorphism
  • Inheritance
  • Encapsulation

The biggest difference between C programming and C++:
C++ is able to use functions with its structures which are called classes instead.

Our introduction to classes (private and public)

1
#include <stdio.h>
 
class rectangle
{
        public: // member functions
 
                int area();
                int perimeter();
                rectangle(); // constructor
                rectangle(int,int); // ~rectangle(); is a destructor
 
        private: // member variables
 
                int length;
                int width;
};
// defining our classes area,perimeter and our constructors
int rectangle::area() //area is a member of the rectangle class due to ::
{
        return((length*width));
}
 
int rectangle::perimeter()
{
        return((2*width)+(2*length));
}
rectangle::rectangle()
{
        length=0;
        width=0;
}
rectangle::rectangle(int length,int width)
{
        this->length=length; //this is used to define itself
        this->width=width;
}
int main()
{
        int area,perimeter;
        area=0;
        perimeter=0;
        rectangle rect1;
        rectangle *rect2;
        rect2=new rectangle(4,10); // rect2 is a new rectangle enter length of 4 width of 10
        //rect1.length=6; does not work since length is a private class.
        area=rect1.area(); // rect1 is not a pointer . is used for structure
        perimeter=rect1.perimeter();
        printf("The rect1's area is: %d\n", area);
        printf("The rect1's perimeter is: %d\n", perimeter);
        area=rect2->area();
        perimeter=rect2->perimeter();
        printf("The rect2's area is: %d\n", area);
        printf("The rect2's perimeter is: %d\n", perimeter);
 
        return(0);
}

Author-David Woodcock
Designer-Derek Southard - I did pretty it up, sorry I was late. I checked before they were wrote to design, then I forgot to come back until now.
Reviewer-Matthew Page

11-06-2014

We did a little modifying from the previous rectangle.cc program we wrote on Tuesday. This one allows us to put in the length and width for rectangle 1 so we no longer get 0 for area and perimeter.

1
#include <stdio.h>
#include<stdlib.h>
 
class rectangle
{
        public: // member functions
 
                int area();
                int perimeter();
                rectangle(); // constructor
                rectangle(int,int); // ~rectangle(); is a destructor
                int getlength(); // accessor methods
                void setlength(int);
                int getwidth();
                void setwidth(int); // end accessor methods
 
        private: // member variables
 
                int length;
                int width;
};
// defining our classes area,perimeter and our constructors
 
int rectangle::area() //area is a member of the rectangle class due to ::
{
        return((length*width));
}
 
int rectangle::perimeter()
{
        return((2*width)+(2*length));
}
 
rectangle::rectangle()
{
        length=0;
        width=0;
}
 
rectangle::rectangle(int length,int width)
{
        this->length=length; //this is used to define itself
        this->width=width;
}
 
int rectangle::getlength()
{
        return(length);
}
 
void rectangle::setlength(int length)
{
        this->length=length;
}
 
int rectangle::getwidth()
{
        return(width);
}
 
void rectangle::setwidth(int width)
{
        this->width=width;
}
 
int main()
{
        int area,perimeter;
        area=0;
        perimeter=0;
        rectangle rect1;
        rectangle *rect2;
        rect2=new rectangle(4,10); // rect2 is a new rectangle enter length of 4 width of 10
        rect1.setlength(6);
        rect1.setwidth(7);
        area=rect1.area(); // rect1 is not a pointer . is used for structure
        perimeter=rect1.perimeter();
        printf("The rect1's area is: %d\n", area);
        printf("The rect1's perimeter is: %d\n", perimeter);
        area=rect2->area();
        perimeter=rect2->perimeter();
        printf("The rect2's area is: %d\n", area);
        printf("The rect2's perimeter is: %d\n", perimeter);
        return(0);
}

Standard ways of defining a class

Public: This means that all of the functions below this(and any variables) are accessible to the rest of the program.NOTE: That is a colon, NOT a semicolon…

Private: Only the Function that contains the private parts can access them.

Protected: This means that all the variables under this, until a new type of restriction is placed, will only be accessible to other functions in the class and child class.

Matt gave us a little preview on inheritance which is what we will be covering next Tuesday. Here is some code and comments we went over at the end of class:

2
class shape // parent class
{
        public:
                shape();
                void setlength(int);
                int getlength();
                void setwidth(int);
                int getlength();
 
        private:
                int length;
                int width;
};
 
class rectangle:public shape
// single : to identify the class that is inheriting (rectanlge is inheriting from shape)
// rectangle is a child of shape
// everything is copied from shape into rectangle
// can only access the parents public parts not private (-_-)
 
{
        public:
                rectangle();
                int area;
                int perimeter();
        private:
                friend int thing; //assigns friendship to a class allowing private variables to be access
};
 
class traingle:public shape //another child, sibling of rectangle
{
        public:
 
};

Author: Sudesh Tiwari
Designer: Zack Golden
Reviewer: David Woodcock

11/11/2014

Inheritance
-We're doing a base class and then from that a derived class.

Today's code included multiple source code files that we archived together into libraries.

Starting with node.h:

1
/************************************************
 *
 * Matthew Page
 *
 * 11/11/2014
 * CSCS 1320 
 *
 * node.h - a header file for something
 *
 *
 * *********************************************/
 
#ifndef _NODE_H     //if not defined, (if it's not included use this, if not skip it.)
#define _NODE_H
#include <cstdlib>
 
class Node {
    public:
        Node();     //constructor
        Node(int);  //2nd constructor
        void setValue(int);   //accessor functions to access the private variable value.
        int getValue();       //accessor functions
    private:
        int value;
};
#endif                        //ending ifndef (if not defined)


Next file, create.cc:

1
/************************************************
 *
 * Matthew Page
 *
 * 11/11/2014
 * CSCS 1320 
 *
 * create.cc - another file for something
 *
 *
 * *********************************************/
 
#include "node.h"
 
Node::Node()
{
    value=0;
}
 
Node::Node(int value)
{
    this->value=value;
}


Next file, value.cc:

1
/************************************************
 *
 * Matthew Page
 *
 * 11/11/2014
 * CSCS 1320 
 *
 * value.cc - another file for something
 *
 *
 * *********************************************/
 
#include "node.h"
 
void Node::setValue(int value)
{
    this->value=value;
}
 
int Node::getValue()
{
    return(this->value);
}


Now we decided to make some directories so within lab46 prompt we run the following commands:

mkdir node


to make a directory called “node.”

mv node.h node


to move node.h into node directory.

mv create.cc node


to move create.cc into node directory.

mv value.cc node


to move value.cc into node directory.

cd node


to change into the node directory.

Now we are creating object files from a couple of these source files, create.cc and value.cc with:

g++ -c create.cc


and:

g++ -c value.cc


and now if you look in the directory with ls:

ls


you can see the create.o and value.o object files.

Now we are going to create a static library which is classified as the older, “classic” library type.
A static library is really just an archive.

Now we create this archive by running:

ar rcs libnode.a create.o value.o


we can see with ls:

ls


That we now have a library file called libnode.a in the directory.

We can extract the object files back out of the archived library file with

ar x libnode.a


Now we are going to make a new directory called “SinglyLinkedNode” with:

cd ..


(gets out of node directory into parent directory)

mkdir SinglyLinkedNode


creates directory called “SinglyLinkedNode”

cd !$


changes into previous argument of last command, which in this case is the same as:

cd SinglyLinkedNode


Now we have a new header file called, SinglyLinkedNode.h:

1
/************************************************
 *
 * Matthew Page
 *
 * 11/11/2014
 * CSCS 1320 
 *
 * SinglyLinkedNode.h - another file for something
 *
 *
 * *********************************************/
 
#ifndef _SINGLY_H
#define _SINGLY_H
#include "node.h"
 
class SinglyLinkedNode:public Node {
    public:
        SinglyLinkedNode();
        SinglyLinkedNode(int);
        SinglyLinkedNode *getNext();
        void setNext(SinglyLinkedNode *);
    private:
        SinglyLinkedNode *next;
};
#endif


Next file, Another, DIFFERENT, create.cc:

1
/************************************************
 *
 * Matthew Page
 *
 * 11/11/2014
 * CSCS 1320 
 *
 * create.cc -  another create.cc file for 
 *              something.
 *
 * *********************************************/
 
#include "SinglyLinkedNode.h"
 
SinglyLinkedNode::SinglyLinkedNode()
{
    this->setValue(0);
    this->next=NULL;
}
 
SinglyLinkedNode::SinglyLinkedNode(int value)
{
    this->setValue(value);
    this->next=NULL;
}


last file, next.cc:

1
/************************************************
 *
 * Matthew Page
 *
 * 11/11/2014
 * CSCS 1320 
 *
 * next.cc - another file for something
 *
 *
 * *********************************************/
 
#include "SinglyLinkedNode.h"
 
SinglyLinkedNode * SinglyLinkedNode::getNext()
{
    return(this->next);
}
 
void SinglyLinkedNode::setNext(SinglyLinkedNode *next)
{
    this->next=next;
}


Now we are creating object files again with these new files, create.cc (the new one) and nect.cc:

g++ -c create.cc


g++ -c next.cc


which should create the two objecty files, create.o and next.o
Actually these may fail because node.h is now in a new location.

So to follow the same error we all did in class we create a new directory, up one level with:

mkdir ../inc


creates a directory called “inc” for includes int he parent directory (along with node and SinglyLinkedNode directories)

mv SinglyLinkedNode.h ../inc>


moves the SinglyLinkedNode.h header file to the inc directory in the parent directory.

mv ../node/node.h ../inc


moves the node.h header file in the node directory int he parent directory into the inc direcotry int he parent directory.

ls ../inc


shoudl show cirrent contents of ../inc which shoudl now include the two header files, SinglyLinkedNode.h and node.h.

Now we can reattempt to create the object files with:

g++ -c create.cc -I ../inc


and then:

g++ -c next.cc -I ../inc


Now if we check the current directory with ls:

ls


It shoudl show the 2 object files, create.o and next.o

Last step (for today, we are actually plannign on building on this for Thursday 11/13/2014) is to archive these object files into a library archive called libSinglyLinkedNode.a with:

ar rcs libSinglyLinkedNode.a create.o next.o


and ls should show this file:

ls


should see libSinglyLinkedNode.a

NOTE: There currently isn't any executable part to this program…yet. We have no main() function.

AUTHOR: Matthew Page
DESIGNER: Dan Shadeck

11/13/2014

Nodes

  • By itself a node is useless.
  • Large companies have organizational units.\
  • productively useless, but organizationally valuable.

SinglyLinkedNode inherits node.

A list of singly linked nodes

A list of singly linked nodes or a singly linked list.

To access the the 3rd node we would go:
a→next→next.

The beauty is that you do not need to know how many nodes you need until runtime.
this is dynamic programming.
the notion of fixed position like we have with arrays, we don;t have with this.

Doubly Linked List - a pointer to next and previous nodes.

Appending/Inserting a node
Appending/Inserting a node.

This is like holding balloons you have to change things in such a way that you don;t lose connection to them.

The code from class today, “nodefun.c” which builds on last class's source files, and is located on the same level as the directories inc, node, and SinglyLinkedNode from last class:

1
/****************************************
 *
 * Matthew Page
 * 
 * 11/13/2014
 * CSCS 1320
 *
 * nodefun.cc - A file for main function, 
 *              I think, building on last
 *              class.
 *
 ***************************************/
 
#include <cstdio>
#include "SinglyLinkedNode.h"
 
int main()
{
    int i;
    SinglyLinkedNode *start=NULL;
    SinglyLinkedNode *tmp=NULL;
    SinglyLinkedNode *tmp2=NULL;
 
    //setting up List of Singly Linked Nodes
    start=new SinglyLinkedNode(7);
    start->setNext(new SinglyLinkedNode(39));
    tmp=start->getNext();
 
    //inserting a new node
    tmp2=new SinglyLinkedNode(73);
    tmp2->setNext(start->getNext());
    start->setNext(tmp2);
 
    //setting tmp to point to starting node
    tmp=start;
 
    //print out our list with a loop
    while (tmp!=NULL)
    {
        printf("%d->", tmp->getValue());
        tmp=tmp->getNext();
    }
    printf("NULL\n");
    return (0);
}

setting pointers to NULL

A List of Singly Linked Nodes (one dimensional) is different from a Singly Linked List of Singly Linked Nodes (two dimensional).

Appending a node

we compile todays code in conjunction with last class's code with the following command:

g++ -o nodefun nodefun.cc -I inc -L SinglyLinkedNode -l SinglyLinkedNode -L node -l node

AUTHOR & DESIGNER: Matthew Page
REVIEWER:Derek Southard.

notes/cprog/cprog-fall2014.txt · Last modified: 2015/01/20 07:14 by 127.0.0.1