User Tools

Site Tools


opus:spring2012:jcavalu3:start

Josh Cavaluzzi's Super-Duper AWESOME Opus!!! YEAH!!

OH YEAH!! OPUSIN' MY STUFF LIKE A BAU5

Introduction

Why, hello! My name is Josh Cavaluzzi. I entered college majoring in Physics and Mathematics, but when I took the C for Engineers class, I found out that I love programming and decided to change my major to Computer Sciences.

Part 1

Entries

Entry 1: February 7, 2012

  • On this date, I found out the proper syntax and usage of arrays in the C Programming language.
  • Arrays are an essential part of programming, because they allow the programmer to input multiple similar variables into specific allocated memory, and from there the programmer can use that array to do many different things in the program.
  • At the moment, the concept of arrays I am set with. I can't think of any problems that have come up.
  • My understanding of arrays comes from C for Engineering, which is a little different because we used the C++ version of arrays, which gave me a little confusion at first, but now all is going well.

Entry 2: February 10, 2012

  • On this date I finally grasped the concept of the data types and what I needed to program into the code to either accept them from the user or display them to the user.
  • With this knowledge, I can easily program code that allows me to accept values and print values that are necessary for the program.
  • The concept of printing characters in an array still confuse me, like the use of %s and %c.
  • With the programming we did February 16, 2012, I began to understand what these mean and what I can do to print single characters instead of strings.

Entry 3: February 9, 2012

  • On this date, the concept of using debugging programs was introduced.
  • Using this method, I was able to find out where a logical error in a program is, and in some cases it can tell me how to fix it.
  • This is very helpful, because logical errors occur often in programs, which doesn't stop the program from compiling. Using this strategy, I can find those logical errors quickly and correct them.
  • I have used this a few times and it has helped quite a bit. It helped with some of the programs I had to write, and I was able to fix them easily.

Entry 4: February 16, 2012

  • On this date, I learned how to take arguments input by the user, assign them to an array, and use them for multiple purposes.
  • Using this method, I am able to print certain code, take the arguments, separate the characters, and use each as their ASCII numbers, and many other things.
  • I used this in the first project, as well as some in class examples.
  • My knowledge of using this method is still lacking a bit, but I am beginning to understand it more.

Keywords

cprog Keywords

Standard I/O (STDIO, STDOUT, STDERR)
Header Files (Local and System), C Standard Library (Libc), Libraries
arithmetic (equations, operators)
logic and operators (and, or, not, xor)
Variables (types, ranges, sizes)

Scope (Block, Local, Global, File)
Pointers (address of, assignment, dereferencing)
Type Casting
Selection Structures (if, case/switch)
Repetition/Iteration Structures (for, while, do while)

Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)
File Access (Read, Write, Append)
Structures (Declaration, Accessing Elements, Pointers to)
typedef, enum, union
Functions, Parameters (Pass by: Value, Address, Reference), Return Types, Recursion, Command-line arguments
Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)
I/O Streams (cin, cout, cerr, stream operators) [C++]
Namespaces [C++]
Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]
Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]
Inheritance (single, multiple Inheritance), Polymorphism/Virtual Functions, Abstract Base Class [C++]
Overloading (Functions, Operators) [C++]
Exception Handing (throw, try, catch) [C++]
Templates, STL (Standard Template Library) [C++]

cprog Keyword 1

Header Files

Definition

A header file is used to allow the programmer to use specific functions. It is used by preceding it with '#include'. (Ex. #include<stdio.h>)

Demonstration

Demonstration of the chosen keyword.

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

/*
 * Sample code block
 */
#include <stdio.h>
 
int main()
{
    printf("This is an example of a header file - stdio.h")
 
    return(0);
}

cprog Keyword 2

Standard I/O

Definition

Standard I/O stands for Standard Input/Output. When in a program, it allows the user to input whatever they need to put into the program, and it allows the program to show text, which can say whatever the programmer wants.

Demonstration

Demonstration of the chosen keyword.

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

/*
 * Sample code here.
 */
#include <stdio.h>
 
int main()
{
    unsigned char randomvar;
    printf("This is the output code - printf. It outputs whatever the programmer wants through text.");
    scanf("%hhu", &randomvar); /* Allows the user to input whatever data
                                * that is necessary.
                                * /
    return(0);
}

cprog Keyword 3

Repetition/Iteration Structures

Definition

Repetition/Iteration Structures consist of for, while, and do-while loops. Each of these loops are often used to fill arrays, accept values and keep asking if the value isn't correct, to accept multiple values, to print multiple values, etc.

Demonstration

Demonstration of Repetition/Iteration Structures

/*
 * Sample code block
 */
 
#include<stdio.h>
#include<stdlib.h>
 
int main()
{
        char *value, i; //Declaring two integers: the pointer "value"
                        //and i as a char
        value = (char*)malloc(sizeof(char)*4); //setting aside 4 bits of memory
                                               //and returning a pointer
        *(value+0) = 0; //assigning the pointer for the first space of allocated$
        *(value+1) = 1; //assigning pointer for the second space of allocated me$
        fprintf(stdout, "Please enter a value (-128-+127):");
        fscanf(stdin, "%hhd", &i);
        *(value+2) = i; //assigns pointer for the third space of allocated memory
                        //gives that memory the value that it is assigned
        *(value+3) = (2*i)+3; //assigns pointer for the fourth space of allocated memory
                              //gives that memory the value that is "calculated"
        for(i=3; i>=0; i--)
        {
                printf("%hhd\n", *(value+i));
        }
        return(0);
}
 
/* What the file is doing is showing how arrays work.
 
        The first pointer assigns 0 to the first space (*(value+0) = 0)
        The second pointer assigns 1 to the second space (*(value+1) = 1)
        The third pointer assigns whatever the user input as i to the                 third space etc, etc.
*/
 
    return(0);
}

cprog Keyword 4

Variables (Type, Ranges, and Sizes)

Definition

Variables are the part of the code that take assignments like numbers or memory. There are many types of variables with different sizes.

Demonstration

Demonstration of the chosen keyword.

/*
 * Sample code block
 */
#include <stdio.h>
 
int main()
{
 
#include <stdio.h>
#include <math.h>
 
int main()
{
        // Signed Variables
        signed char sc = 0;
        signed short int ssint = 0;
        signed int sint = 0;
        signed long int slint = 0;
        signed long long int sllint = 0;
 
        // Unsigned Variables
        unsigned char uc = 0;
        unsigned short int usint = 0;
        unsigned int uint = 0;
        unsigned long int ulint = 0;
        unsigned long long int ullint = 0;
 
        // Junk Variable
        unsigned long long int quantity = 0;
 
    return(0);
}

cprog Keyword 5

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

Definition

Logic gates are used in if blocks, loops, switch blocks, and other functions. The purpose of these logic gates is to take two or more input statements and see if the output is true or false, and perform a specific task, in most cases, with that specific output. Operators are the signs that do a specific task, like add “+”, subtract “-”, etc.

Demonstration

* A few examples of operators are greater than “>”, less than “<”, is equal to “==”, etc. * A few examples of logic gates are AND “&&”, OR “||”, NOT “!=”, etc.

/*
 * Sample code block
 */
 
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        char *word, len = 0, x, pos = 0;
        word = (char *) malloc(sizeof(char)*24);
        fprintf(stdout, "Please enter a word: ");
        fscanf(stdin, "%s", word);
        printf("Debug A\n");
        x = *(word + pos);
        while((x!='\0')&&(x != '\n')) // Specifically the "&&" and the "!="
        {
                printf("COME ON! x is %hhd\n", x);
                printf("pos is %hhd\n", pos);
                len++;
                pos++;
                x = *(word + pos);
        }
        printf("Debug B\n");
        for(pos = len; pos > -1; pos--)
        {
                fprintf(stdout, "%c", *(word + pos));
        }
        fprintf(stdout, "\n");
        printf("Debug C\n");
        return(0);
}

cprog Keyword 6

Functions, Parameters

Definition

Functions are specific blocks of code that were either created with the standard library of code or are created separately in each program. The purpose of these functions vary, but the main idea of functions is that they are created to perform a certain operation that can be used to further the process of the program that it is used in. The parameters are the variables that are called in the function, and are brought in through the function call.

Demonstration

Demonstration of the chosen keyword.

/*
 *
 * Sample code block for functions and parameters.
 *
 */
#include<stdio.h>
 
int function( int prntnum ) //I cleverly labeled the function of this program "function" and the parameter "prntnum".
{
        char i;
        for(i=0; i < 10; i++)
        {
                prntnum++;
        }
        return(prntnum);
}
 
int main()
{
        int parameter = 0;
        printf("The value of the original parameter is: %d\n", parameter);
        printf("The new value of the parameter is: %d\n", function( parameter ));
        return(0);
}

Results:

lab46:~/src/cprog/Opus/Opus1$ ./Keyword6
The value of the original parameter is: 0
The new value of the parameter is: 10
lab46:~/src/cprog/Opus/Opus1$ 

cprog Keyword 7

Selection Structures (if, case/switch)

Definition

Selection Structures are used to decide if a program will continue or which path it will take. If blocks are used with '!=' (not equal to), '&&' (and), '||' (or), etc. Case/Switch blocks are used a great amount of the time as “menus” that the user can choose from.

Demonstration

Demonstration of the chosen keyword.

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

/*
 * Sample code block for Selection Structures
 */      
#include<stdio.h>
#include<stdlib.h>
 
int main()
{
        int *input, *pick;  input=pick=NULL;
        input=(int *)malloc(sizeof(int)*1);
        pick=(int *)malloc(sizeof(int)*1);
        *input=0;
        *pick=0;
        while(*pick != -1)
        {
                srand(time(NULL));
                *pick=rand()%99+1;
                printf("Guess the computer's pick: ");
                scanf("%d", input);
                if(*input==*pick) //This is the first if block
                {
                        printf("Wow! You got $it right!!!!\n");
                }
                else if(*input > *pick)
                {
                        printf("Too low!!!\n");
                }
                else
                {
                        printf("Too high!!\n");
                }
                printf("Computer had %d\n", *pick);
                printf("0 to go again, -1 to quit\n");
                scanf("%d", pick);
        }
        return(0);
}

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

cprog Keyword 8

Arithmetic (Equations, Operators)

Definition

Arithmetic is used to perform operations that the computer has to run so it can run programs. Equations are solved to find a result that the user is looking for. Operators are used in equations, examples are +, -, /, and *.

Demonstration

Demonstration of the chosen keyword.

/*
 * Sample code block
 */
#include<stdio.h>
#include<stdlib.h>
 
int main()
{
        FILE *in, *out;
        char value=0;
        in=fopen("file.txt", "r");
        out=fopen("out.txt", "w");
        if(in == NULL)
        {
                printf("ERROR!\n");
                exit(1);
        }
        fscanf(in, "%hhd", &value);
        while(value!=-1)
        {
                value*=2; // This is an equation, which means "value = value * 2", the operator being *
                fprintf(out, "%hhd\n", value);
                fscanf(in, "%hhd", &value);
        }
        fclose(in);
        fclose(out);
        return(0);
}

cprog Objective

cprog Objective

The objective of the course is to learn C/C++ Programming language and use that to learn about computers and programming more. Also, programming in general is important.

Definition

This includes learning about anything from arrays(blocks of memory to store similar variables) to variables. All that will be taught to me is important in taking my next step into the beautiful world of programming and technology!

Method

I will be using the books I have purchased, my professor, and other students as resources to help myself grasp the concept of computer programming and all that it controls.

Measurement

On a scale of Red to Blue, I would say I am at a well… A well of knowledge and understanding! No, but seriously, I understand most of the concepts. The trouble I have is that:

1. I procrastinate 2. Putting together my own code from scratch becomes a little troublesome, especially since I learned mostly C++ and then jumped into this new atmosphere of C, with the compiler that comes with Ubuntu and Linux.

It is all a little confusing at times, but I feel that I will get the hang of it.

Analysis

I'm still quite fuzzy on how I am to fill this out, but I am going to try my best to answer these correctly.

  • I think I am doing alright.
  • There is always room for improvement, but specifically I just need to understand pointers and addresses a little more.
  • I believe that it could have been, but that is a job for the next Opus!
  • I do believe that an enhancement would be very important; it would allow me to further test my abilities in C.
  • It could be altered by including more that I will learn and need to learn to make myself better at programming and understanding computers.

I apologize if this is completely incorrect. I tried to fill it out to the best of my ability. Unfortunately, my abilities are lacking at the moment because it is very late for me and once it gets late, my brain flies out the window, and it takes me a little while (and some quality sleep) to get it back and functional!

Experiments

Experiment 1

Question

What would be printed if I replace the %u with the $d for an unsigned integer?

Resources

According to classes being taken, %d represents a signed integer, while %u represents an unsigned integer. The range for a signed integer data type is -2,147,483,647 to 2,147,483,646, while the range for an unsigned integer data type is 0 to 4,294,967,295.

Hypothesis

I believe that the printed value will be the same ONLY if it is within the range of the signed integer data type. Ex. If the user inputs a value between 0 and 2,147,483,647, then it should print out fine, but if the value is greater than that range, then the value will “roll over” to the next integer in the signed integer data type, which would make the value a negative number.

Due to the data type only covering positive numbers (unsigned integer), it can go to larger numbers in the 4 bytes it is given for memory, but if it is printed as a signed integer, then it will only be able to print out half of the positive integers that it could as an unsigned integer, so it will go back over into the negative numbers until it satisfies the amount of digits it has.

Experiment

To run this experiment, I am going to use the Lab46 terminal and create a program that will accept a value ranging from 0 to 4,294,967,295, which will be accepted as a unsigned integer. From there, the program will print the value back out as a signed integer using the %d command.

Data

This is the code that I used:

#include<stdio.h>

int main()
{
        unsigned int integer;

        printf("Please input any integer between 0 and 4,294,967,295: ");
        scanf("%u\n", &integer);
        printf("The number you put into the program is: %d\n\n", integer);
        return(0);
}

This is the result:

lab46:~/src/cprog$ ./experiment1
Please input any integer between 0 and 4,294,967,295: 3015489756
1
The number you put into the program is: -1279477540

lab46:~/src/cprog$ 

Analysis

Based on the data collected:

  • My hypothesis was correct.
  • My hypothesis was applicable because the number did roll over because it was too large to be included as a positive integer, so it just ran back as a negative number.
  • Yes, much more is going on than I originally thought. I can mix it up.
  • I tried to run the program and it did not work. It was able to run, and I fixed it.
  • The data was what I was expecting.

Conclusions

When using an unsigned data type, it is possible to print that number as a signed data type, the only problem is that if it is larger than the range given, then it will just “roll over” until the entire number has been stored.

Experiment 2

Question

What would result from manipulating the “firstarray.c” program and replacing the “*4” with a “*3” and nothing else?

Resources

According to what I have learned so far, the purpose of the “*4” along with the function malloc is to allocate memory that the program can then store whatever it needs to in. This is one way to create an array. The “*4” in this program specifically multiplies the size of the char data type, which is one bit, and multiplies that by 4, leaving 4 bits of space that the program can store data in.

Hypothesis

My best guess would be that the array will only have three char-sized “blocks” of memory that are available for storage. This will cause the fourth assignment in the array (*(array + 3)) to not be assigned to any block of memory in the array. This shouldn't cause any problems with the compiler, the program should run fine, still.

Experiment

To perform this experiment, I have used a program from class and manipulated it, replacing the 4 with a 3 when sizing the array. The program then prints out what is left, and I believe that the program will print out a bunch of randomness when it gets to the fourth block of memory that was supposed to be created.

Data

This is the program, minus the documentation:

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

int main()
{
        char *value, i; //Declaring two integers: the pointer "value"
                        //and i as a char
        value = (char*)malloc(sizeof(char)*3);
                                              
        *(value+0) = 0;
        *(value+1) = 1;
        fprintf(stdout, "Please enter a value (-128-+127):");
        fscanf(stdin, "%hhd", &i);
        *(value+2) = i;
                        
        *(value+3) = (2*i)+3;
                              
        for(i=3; i>=0; i--)
        {
                printf("%hhd\n", *(value+i));
        }
        return(0);
}

These are the results of the program:

lab46:~/src/cprog/Opus/Opus1$ ./experiment2
Please enter a value (-128-+127):15
33
15
1
0
lab46:~/src/cprog/Opus/Opus1$ ./experiment2
Please enter a value (-128-+127):458
-105
-54
1
0
lab46:~/src/cprog/Opus/Opus1$ ./experiment2
Please enter a value (-128-+127):12
27
12
1
0
lab46:~/src/cprog/Opus/Opus1$ 

Analysis

Based on the data collected:

  • My hypothesis was incorrect.
  • My hypothesis was applicable. When the memory was allocated, a little bit of “buffer” memory was saved, as well, which allowed the last value to be stored when it was compiled.
  • I didn't think that there would be any more memory left to store that value in, but it seems that there is more to the allocation of memory than I thought.
  • The chance of storing a variable in an array when the program doesn't specifically make the memory for it is one that I did not think would happen.
  • The lack of memory allocation didn't stop the number from kicking down the array's door and walking right in!

Conclusions

Through this experiment, I realized that there is more to arrays and memory allocation than I thought. There is a chance that variables may be stored in buffer memory when making an array, and that is what happened in this experiment. I also learned that I need to read up on my arrays.

Experiment 3

Question

Is it possible to multiply things in an array and store the result in the array?

Resources

From what I have learned about arrays, arrays are capable of a lot of different functions, like storing related variables, and either reading them out or using them for another purpose. So far, arrays have been used to store values and re-arrange them, read them back out, to take variables from one function and use them in another, and many other purposes.

Hypothesis

I believe that this is possible, because arrays store similar variables, even if they are combined in some way and stored back into it.

Experiment

I will make a program that creates an array that will allow the user to store two integer numbers between one and one hundred into the array. From there, the program will call those two numbers from it, and multiply the two numbers together, then storing the third in the array. The array will then be printed.

Data

The program for the experiment:

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

int main()
{
        int storage1 = 0;
        int storage2 = 0;
        int *array;
        array = (int*)malloc(sizeof(int)*3);

        fprintf(stdout, "Please enter two numbers between 1 and 100:\n");
        fscanf(stdin, "%u", &storage1);
        fscanf(stdin, "%u", &storage2);
        *(array) = storage1;
        *(array+1) = storage2;
        *(array+2) = (*(array+1)) * (*(array));
        fprintf(stdout, "These are the numbers stored in the array:\n%u\n%u\n%u$
        return(0);
}

The results:

<cli> lab46:~/src/cprog/Opus/Opus1$ ./experiment3 Please enter two numbers between 1 and 100: 10 15 These are the numbers stored in the array: 10 15 150 lab46:~/src/cprog/Opus/Opus1$ ./experiment3 Please enter two numbers between 1 and 100: 100 100 These are the numbers stored in the array: 100 100 10000 lab46:~/src/cprog/Opus/Opus1$

Analysis

Based on the data collected:

  • My hypothesis was correct.
  • My hypothesis was applicable.
  • What I thought was basically what happened, although I did think that due to the fact that I had to use the “*” symbol in the arrays and for multiplication, I thought that there may be some confusion in the program that would have caused an error.
  • The program didn't have a check for any numbers below one or above 100, even though the number could have been much, much greater than 100. (Not lower than one, because any number below zero doesn't technically exist for the unsigned integer data type)
  • Had I put in a number that caused the result to be greater than the threshold for integer data types, the result would have been incorrect by mathematical terms, and so the program would not have looked as if it worked, although it was fully functional and correct.

Conclusions

Arrays can be very useful when it comes to storing numbers and variables that you may need later or in other functions. An array could be created to take multiple numbers and use these numbers to show different operations and what the result of these operations would be.

Part 2

Entries

Entry 5: March , 2012

  • On this day, I learned about unions and how they are used in programming.
  • Unions use the ability to hold multiple variables of different data types in the same memory location and allow the program to call from the union when the variables are necessary.
  • The downside to the use of unions is that when the program uses the first variable and stores something for use in the second variable, the union scraps the old value and inputs the new one in the union. Basically, the union uses “one space” of memory for all the variables in the union.
  • When the program calls these variables, the variable is represented by the name of the union, a period, and then the name of the variable.
  • EXAMPLE:

If the union is named value, and the variables are [float f, int x], then when called, the variables will be value.f for the float variable, and value.x for the int variable.

Entry 6: March 6, 2012

  • On this day, I learned about the declaration typedef and what it's function is.
  • The purpose of typedef is to allow the programmer to create new data type names for the program's variables.
  • This allows the programmer to change data type names for organization purposes or to possibly shorten some data types.
  • And example of this would be:
 **//typedef//** int length; 

This would cause the int length to shortened to just length:

 length max, min; 

Entry 7: March 22 (I think), 2012

  • On this date, I coded one of the most important things in programming: AND, OR, and NOT logic gates in C++.
  • By doing this, I learned more about what they do, how they are used, and how to combine them and create other logic gates.
  • This helped me become better acquainted with C++ programming, which is another thing that I learned recently.
  • It was difficult to comprehend at first, but once I sat down and went through what I had typed up to begin with, everything started to make sense.

Entry 8: March 13, 2012

  • On this day, we began learning about C++ programming.
  • C++ programming is seen as an addition to C programming. It is used for Object-Oriented coding.
  • I learned about C++ in the C for Engineers class that I took in the fall, but what I am being taught now is much different, and I like it more.
  • So far, C++ is fairly easy to understand and use. I think I will get the hang of the new stuff soon.

Keywords

cprog Keywords

Scope (Block, Local, Global, File)
Pointers (address of, assignment, dereferencing)
Type Casting
Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)
File Access (Read, Write, Append)

Structures (Declaration, Accessing Elements, Pointers to)
typedef, enum, union
Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)
I/O Streams (cin, cout, cerr, stream operators) [C++]
Namespaces [C++]
Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]
Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]
Inheritance (single, multiple Inheritance), Polymorphism/Virtual Functions, Abstract Base Class [C++]
Overloading (Functions, Operators) [C++]
Exception Handing (throw, try, catch) [C++]
Templates, STL (Standard Template Library) [C++]

cprog Keyword 9

Pointers (address of, assignment, dereferencing)

Definition

Pointers are used to represent a specific address or memory. This is commonly used to store values into variables. Also, pointers can be used as arrays. When a pointer is used, it can allow the program to point to a specific space of memory that can then be used to continue the program for whatever specific purpose it has.

Demonstration

Demonstration of the chosen keyword.

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

#include<stdio.h>

/* In this file, I will be working with pointers and
learning how to use them, if any edits are necesary, they
will be added. Bare with me! */

int main()
{
        int v=17; // Initializing and assigning a value
        int *p1=NULL;
        printf("v is %u\n", v);
        p1=&v;
        printf("*p1 is %u\n", *p1); //Prints *p1
        *p1=53; //Assigns 53 to what p1 points to
        printf("v is %u\n", v);
        printf("*p1 is %u\n", *p1);
        v=7;
        printf("v is %u\n", v);
        printf("*p1 is %u\n", *p1);
        return(0);
}
lab46:~/src/cprog$ gcc -o pointer pointer.c
lab46:~/src/cprog$ ./pointer
v is 17
*p1 is 17
v is 53
*p1 is 53
v is 7
*p1 is 7
lab46:~/src/cprog$ 

cprog Keyword 10

Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)

Definition

Arrays have the capability of storing multiple values of the same type. Arrays that are made without pointers are created as follows:

float array[5];

float: the data type array: the name of the array [5]: size of the array (when assigning values to the array, never assign to the array value [5], only values [0] through [4] exist in the array)

Demonstration

Demonstration of the chosen keyword.

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

#include<stdio.h>
#include<stdlib.h>
 
int main()
{
        int array[5];
        int count;
        int fives = 0;
        printf("{ ");
        for(count = 0; count < 5; count++)
        {
                array[count] = fives;
                fives = fives + 5;
                printf("%d", array[count]);
                if( count < 4 )
                        printf(", ");
                else
                        printf(" }\n");
        }
        return(0);
}
lab46:~/src/cprog/Opus/Opus2$ ./arraykeyword
{ 0, 5, 10, 15, 20 }
lab46:~/src/cprog/Opus/Opus2$ 

cprog Keyword 11

File Access (Read, Write, Append)

Definition

The concept of File Access is what allows programs to read, write, or adjust files. This is used for things like reading a file to a program, writing to a file from a program, or adjusting something in a program. Those are just simple examples, there are many more examples of File Access.

Demonstration

Demonstration of the chosen keyword.

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

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

int main()
{
        FILE *in, *out;
        char value=0;
        in=fopen("file.txt", "r");
        out=fopen("out.txt", "w");
        if(in == NULL)
        {
                printf("ERROR!\n");
                exit(1);
        }
        fscanf(in, "%hhd", &value);
        while(value!=-1)
        {
                value*=2;
                fprintf(out, "%hhd\n", value);
                fscanf(in, "%hhd", &value);
        }
        fclose(in);
        fclose(out);
        return(0);
}

cprog Keyword 12

I/O Streams (cin, cout, cerr, stream operators) [C++]

Definition

I/O Streams serve the same purpose as Standard I/O. The exception is that I/O Streams are used only in C++. A programmer can still use Standard I/O, only by manipulating the header that you are calling it with.

Demonstration

Demonstration of the chosen keyword.

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

#include <iostream>
 
using namespace std;
 
int main()
{
        int value = 0;
        cout << "Listen to me! You have to get out of here!\n\nPlease enter a number:\n";
        cin >> value;
        cout << endl << value << endl;
        return(0);
}

Results:

lab46:~/src/cprog/Opus/Opus2$ g++ -o keyword12 keyword12.cc 
lab46:~/src/cprog/Opus/Opus2$ ./keyword12 
Listen to me! You have to get out of here!

Please enter a number:
15

15
lab46:~/src/cprog/Opus/Opus2$

cprog Keyword 13

typedef, enum, union

Definition
 * Typedef allows the programmer to assign a new data type name to variables, usually to make variables name more convenient and organized.
 * Enum is a constant known as an enumeration constant, which represents a list of constant integer values.
 * A union is used to store multiple values of different data types and keep track of them and what is being assigned to them.
Demonstration

A good example of typedefs and unions exists in the program that was created in class called union.c:

#include<stdio.h>
 
int main()
{
        int i;
        union var {
                int x;
                float f;
        }; //This union holds two values of different data types that will be used accordingly.
        typedef union var Uif;
        //Without ^, we would have had to type "union var value;"
        Uif value;
        for(i = 0; i < 24; i++)
        {
                value.x = value.x + rand()%51 + 1;
        }
        printf("total is : %d\n", value.x);
        value.f = 0.0;
        for(i = 0; i < 73; i++)
        {
                value.f = value.f + rand()%27 + 0.1;
        }
        printf("total is: %f\n", value.f);
        return(0);
}

cprog Keyword 14

Type Casting

Definition

Type casting allows the programmer to use a variable, like int, as another type, like short int or char, for one operation.

Demonstration

The following is an example of type casting:

#include<stdio.h>
#include<stdlib.h>
 
void main()
{
        int num;
        num = 67;
        printf("%c\n", num);
}

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

lab46:~/src/cprog/Opus/Opus2$ ./keyword14
C
lab46:~/src/cprog/Opus/Opus2$ 

cprog Keyword 15

Scope (Block, Local, Global, File)

Definition

The scope of a variable determines how the variable can be used. The block scope means that a variable is used in one specific block or statement. A local scope means a variable can be used in a block as well as any other blocks inside of that first one. A global scope means a variable can be used outside of any block. A file scope means a variable is taken from a file or given to a file.

Demonstration

Demonstration of the chosen keyword.

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

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

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

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

cprog Keyword 16

Overloading (functions, operators) [C++]

Definition

Overloading is when a name is used for multiple functions or operators in a scope. Function overloading means that there are multiple functions with the same name; what makes them different is that each has a different amount or data types of parameters.

Demonstration

Demonstration of the chosen keyword.

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

#include<iostream>
using namespace std;
 
void print( double valuef ) // The function that prints the float value
{
        cout << "Printing the float value: " << valuef << "\n";
}
 
void print( int valuei ) // The function that prints the integer value
{
        cout << "Printing the integer value: " << valuei << "\n";
}
 
int main()
{
        print(15); // Both functions are called print, just with different para$
        print(15.23);
        return(0);
}

This is the result:

lab46:~/src/cprog/Opus/Opus2$ ./keyword16
Printing the integer value: 15
Printing the float value: 15.23
lab46:~/src/cprog/Opus/Opus2$ 

cprog Objective

cprog Objective

One of the course objectives is to be able to break down and separate code into functions and illustrate the use of parameter passing.

Definition

The main purpose of doing this is to reduce the amount of coding in the main function, to make things neater, and to reduce the chances of error in the program. This is done by taking parts of programs that are repeated often within the main function, and remove this code and put it into a function. Then, the programmer will create a function prototype for the function, and replace the repeated code with the function call.

Method

A good method of showing this is shown in project two. A lot of the program that could be used in the main are, instead, put into separate functions, and then called in the main, making the main function much cleaner, and allowing the user to debug with more ease.

Measurement
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
 
void printary( int, char* );
char* mkArray( int );
char* mkZero( int, char* );
char* Addition( int, char*, char*, char* );
//char* Subtraction( int, char*, char*, char* );
 
int main()
{
        char *array1, *array2, *carry, *result, menuchoice;
        int size, size1, size2, count, i;
        fprintf(stdout, "When you input the numbers, you must add an extra zero at the beginning of the larger number, \
or else the program will not run correctly.\n");
        fprintf(stdout, "Also, you must add in enough zeros at the beginning of the smaller numbers to be the same amount of digits as the \
larger, then add one more.\n");
        fprintf(stdout, "Example: If the first number is 12, and the second is 2634, then the first number must have three zeros in front \
of the actual number: 00012.\nThe second number must then have one zero put in front of it: 02634.\n\n\n");
        fprintf(stdout, "The first number must be the smaller number.\n");
 
        fprintf(stdout, "How many digits is this number: ");
        fscanf(stdin, "%hhu", &size1);
        fprintf(stdout, "\nHow many digits is the second number: ");
        fscanf(stdin, "%hhu", &size2);
 
        if( size1 > size2 )
                size = size1;
        else
                size = size2;
 
        size = size++;
 
// Creating the arrays
 
        array1 = mkArray( size );
        array2 = mkArray( size );
        carry = mkArray( size );
        result = mkArray( size );
 
// Making the array values zero
 
        array1 = mkZero( size, array1 );
        array2 = mkZero( size, array2 );
        carry = mkZero( size, carry );
        result = mkZero( size, result );
 
        printary( size, result );
        printary( size, array1 );
        printary( size, array2 );
        printary( size, carry );
 
        fprintf(stdout, "Please enter the number that you want to be stored: ");
 
        fgetc(stdin);
 
        for(i = 0; i <= size; i++)
        {
                *(array1 + i) = fgetc(stdin) - 48;
        }
        printary( size, array1 );
 
        fprintf(stdout, "\n\n");
 
        fprintf(stdout, "Please enter the number that you want to be stored: ");
 
        for(i = 0; i < size; i++)
        {
                *(array2 + i) = fgetc(stdin) - 48;
        }
        printary( size, array2 );
 
        fprintf(stdout, "\n\n");
 
        fprintf(stdout, "What would you like to do with these numbers? ");
        printf("Choose:\n 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Divison\nEnter now: ");
 
        fgetc(stdin);
        menuchoice = fgetc(stdin);
        switch( menuchoice )
        {
                case'1':
                        fprintf(stdout, "You have chosen Addition.\n");
                        result = Addition( size, array1, array2, carry );
                        fprintf(stdout, "The result is: ");
                        printary( size, result );
                        fprintf(stdout, "\n");
                        break;
                case'2':
                        fprintf(stdout, "You have chosen Subtraction.\n");
                        break;
        }
        return(0);
}
 
void printary( int size, char *array )
{
        char count;
        for( count = 0; count < size; count++ )
        {
                printf("%hhu", *(array + count));
        }
        printf("\n");
}
 
char * mkArray( int size )
{
        char *array;
        array = (char *) malloc (sizeof(char) * size);
        return array;
}
 
char * mkZero( int size, char *array )
{
        char count = 0;
        while( count <= size )
        {
                *( array + count ) = 0;
        }
        return array;
}
<
char * Addition( int size, char *array1, char *array2, char *carry )
{
        int count;
 
        int answer = 0;
        char *addition;
        addition = (char *) malloc (sizeof(char) * ( size - 1 ) );
 
        for( count = size; count >= 0; count-- )
        {
                answer = (*(array1 + count) + *(array2 + count) + *(carry + count));
                if(answer > 9)
                {
                        answer = answer - 10;
                        *(carry + (count - 1)) = 1;
                }
                *(addition + count) = answer;
        }
        return addition;
}
Analysis

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

  • I still have some errors to sort through, but the program mostly works. I think I handled it fairly well.
  • There is still room for improvement, I had a lot of trouble making the first few functions and getting them to work properly.
  • I could have cleaned up the functions or used one function to make all of the arrays.
  • I don't believe it would have been efficient, it would have made things very complicated and it would have left too much room for error.
  • I think it is pretty applicable.

Experiments

Experiment 4

Question

What is the difference between using the fgetc() function and the fscanf() function?

Resources

According to a wiki on the website http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/, fscanf's purpose is: “Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments.” This means that fscanf takes a stream that is input and stores that stream into a variable with a specified data type. According to a similar wiki on the same website, the function fgetc's purpose is: “Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced by one character to point to the next character.” In other words, fgetc takes a string and returns whatever it is being pointed to, character by character, until the string ends. One can take a variable and assign it these values.

Hypothesis

I think that these two do very similar things, but the main difference is that a programmer can determine a variable data type with fscanf, while fgetc will always return a character. I that they will do the same thing when the data type of the value in the fscanf function is char, but other than that, you will get different results.

Experiment

I will create a program that accepts the same value through both fgetc and fscanf and assigns them to different variables of the same data type. Then, I will use some fprintf functions to print these values, once as a char, and once as an int.

Data

Experiment:

#include<stdio.h>
#include<stdlib.h>
 
int main()
{
        int scanvalue;
        int fgetcvalue;
        fprintf(stdout, "Input one number twice: ");
        fscanf(stdin, "%d", &scanvalue);
        fgetcvalue = fgetc(stdin);
        fprintf(stdout, "FSCANFVALUE being printed as an integer: %d\n", scanvalue);
        fprintf(stdout, "FGETCVALUE being printed as an integer: %d\n", fgetcvalue);
        fprintf(stdout, "FSCANFVALUE being printed as a character: %d\n", scanvalue);
        fprintf(stdout, "FGETCVALUE being printed as a character: %d\n", fgetcvalue);
        return(0);
}

Result:

lab46:~/src/cprog/Opus/Opus2$ ./experiment4
Input one number twice: 10
FSCANFVALUE being printed as an integer: 10
FGETCVALUE being printed as an integer: 10
FSCANFVALUE being printed as a character: 10
FGETCVALUE being printed as a character: 10
lab46:~/src/cprog/Opus/Opus2$ ./experiment4
Input one number twice: 10 10
FSCANFVALUE being printed as an integer: 10
FGETCVALUE being printed as an integer: 32
FSCANFVALUE being printed as a character: 10
FGETCVALUE being printed as a character: 32
lab46:~/src/cprog/Opus/Opus2$ ./experiment4
Input one number twice: 4 
FSCANFVALUE being printed as an integer: 4
FGETCVALUE being printed as an integer: 32
FSCANFVALUE being printed as a character: 4
FGETCVALUE being printed as a character: 32
lab46:~/src/cprog/Opus/Opus2$ 

Analysis

Based on the data collected:

  • My hypothesis was not correct, it seems that the data type of the variable that the fgetc function is storing the input is what matters.
  • My hypothesis was relevant, but the trouble that comes is when fgetc accounts for the spaces, which fscanf does not account for.
  • There is more than I thought going on, the function accounts for the data type of the value that the input is being stored into, which I didn't think happened.
  • Like I stated, all input is taken when running fgetc, which could cause a problem with the output.
  • There don't seem to be any shortcomings in my data.

Conclusions

What this experiment helped me understand is that fgetc and fscanf are applicable when accepting input, but I should watch out for any extra input, like enter, space, backspace, etc.

Experiment 5

Question

When given two different arrays with different values in them, what would happen if you set one equal to the other?

Resources

According to what I have learned, an array, when set equal to another array, as a pointer, will only have the array point to the address of the other.

Hypothesis

I think that the array that will be set equal to another array will point to the address of the other, changing what memory it holds to the same memory as the other array. I have used this method a lot, and, so far, all I have seen is this result. Testing it now!

Experiment

I will create code that will take two arrays, with different values stored in them, and set one equal to the other, and then reverse them and set them equal to each other. I will print each of the arrays before and after this switch of values.

Data

DA CODE:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        char *array1, *array2;
        int i;
        array1 = (char *) malloc (sizeof(char) * 4 );
        array2 = (char *) malloc (sizeof(char) * 4 );
 
        printf("Input a 4 letter word: ");
        for( i = 0; i <= 3; i++ )
        {
                *( array1 + i ) = fgetc( stdin );
        }
 
        for( i = 0; i <= 3; i++ )
        {
                printf("%c", *( array1 + i ) );
        }
 
        getchar();
 
        printf("\nInput a 4 letter word: ");
        for( i = 0; i <= 3; i++ )
        {
                *( array2 + i ) = fgetc( stdin );
        }
 
        for( i = 0; i <= 3; i++ )
        {
                printf("%c", *( array2 + i ) );
        }
 
        array1 = array2;
        array2 = array1;
 
        printf("\nArray1: ");
 
        for( i = 0; i <= 3; i++ )
        {
                printf("%c", *( array1 + i ) );
        }
 
        printf("\nArray2: ");
 
        for( i = 0; i <= 3; i++ )
        {
                printf("%c", *( array2 + i ) );
        }
 
        printf("\n");
        return 0;
}

The result:

lab46:~/src/cprog/Opus/Opus2$ ./experiment5 
Input a 4 letter word: Cavo
Cavo
Input a 4 letter word: Josh
Josh
Array1: Josh
Array2: Josh
lab46:~/src/cprog/Opus/Opus2$ ./experiment5
Input a 4 letter word: Josh
Josh
Input a 4 letter word: Cavo
Cavo
Array1: Cavo
Array2: Cavo
lab46:~/src/cprog/Opus/Opus2$ 

Analysis

Based on the data collected:

  • Was your hypothesis correct?

– My hypothesis was correct, the first time one was assigned to the other, it dropped it's previous memory assignment and pointed to the new one.

  • Was your hypothesis not applicable?

– I believe my hypothesis was applicable.

  • Is there more going on than you originally thought? (shortcomings in hypothesis)

– There doesn't seem to be more than I thought going on.

  • What shortcomings might there be in your experiment?

– There weren't any shortcomings, FOR THE FIRST TIME, I MADE CODE AND IT RAN JUST AS I WANTED IT TO! NO PROBLEMS!

  • What shortcomings might there be in your data?

– My data was correct and accounted for!

Conclusions

I can conclude that my knowledge of arrays has increased, and is pretty good, now. Probably due to the great amount of arrays and array passing in projects 2 and 3.

Retest 2

Perform the following steps:

State Experiment

Whose existing experiment are you going to retest? Provide the URL, note the author, and restate their question.]

– I will be retesting Robert Matsch's third experiment, asking what happens if one accidentally puts ' in instead of .

URL: http://lab46.corning-cc.edu/opus/spring2012/rmatsch/start#experiment_3

Resources

Evaluate their resources and commentary. Answer the following questions:

  • Do you feel the given resources are adequate in providing sufficient background information?

– He stated one resource, the C ANSI book that was purchased for the class. I believe that this would give enough information about the experiment.

  • Are there additional resources you've found that you can add to the resources list?

– The interwebs!

  • Does the original experimenter appear to have obtained a necessary fundamental understanding of the concepts leading up to their stated experiment?

– I believe he has, it gave him many errors, so I believe that he could understand that it isn't a good thing to do. (I hope)

  • If you find a deviation in opinion, state why you think this might exist.

– I have no objections. Everything seems to be in order!

Hypothesis

State their experiment's hypothesis. Answer the following questions:

  • Do you feel their hypothesis is adequate in capturing the essence of what they're trying to discover?

– Yeah, I believe that it covers anything they may see.

  • What improvements could you make to their hypothesis, if any?

– I think that he could have added more explanation, but mainly a spellcheck! :x

Experiment

Follow the steps given to recreate the original experiment. Answer the following questions:

  • Are the instructions correct in successfully achieving the results?

– They are correct, there isn't much more one can do when testing to see if it works or not.

  • Is there room for improvement in the experiment instructions/description? What suggestions would you make?

– I have no suggestions.

  • Would you make any alterations to the structure of the experiment to yield better results? What, and why?

– I would have added the result of the working code as well, and I would have just attempted to run the incorrect code, just to show the reader what happens. That could give the reader more piece of mind on the matter.

Data

Publish the data you have gained from your performing of the experiment here.

The code of the correctly done program:

#include <stdio.h>
 
int main()
{
        printf("Hello, World!\n");
        return 0;
}

the code of the incorrectly done program:

#include <stdio.h>
 
int main()
{
        printf('Hello, World!');
        return 0;
}

The result of the correctly done program, followed by the result of the incorrectly done program:

lab46:~/src/cprog/Opus/Opus2$ gcc -o retest retest.c
lab46:~/src/cprog/Opus/Opus2$ gcc -o retestwrong retestwrong.c
retestwrong.c:5:9: warning: character constant too long for its type
retestwrong.c: In function 'main':
retestwrong.c:5: warning: passing argument 1 of 'printf' makes pointer from integer without a cast
/usr/include/stdio.h:339: note: expected 'const char * __restrict__' but argument is of type 'int'
lab46:~/src/cprog/Opus/Opus2$ ./retest
Hello, World!
lab46:~/src/cprog/Opus/Opus2$ ./retestwrong
Segmentation fault
lab46:~/src/cprog/Opus/Opus2$ 

Analysis

Answer the following:

  • Does the data seem in-line with the published data from the original author?

– The data that I have seems nearly identical to the data that Rob had.

  • Can you explain any deviations?

– There were no deviations.

  • How about any sources of error?

– The only errors were the expected ones that came with only putting ' instead of .

  • Is the stated hypothesis adequate?

– The stated hypothesis was adequate, he seemed to know what the result would be.

Conclusions

Answer the following:

  • What conclusions can you make based on performing the experiment?

– I concluded that when putting a ' symbol in for a symbol in printf statements, an error occurs. I wasn't sure if something else would happen, which is why I chose this experiment.

  • Do you feel the experiment was adequate in obtaining a further understanding of a concept?

– Absolutely, this experiment helped me to determine the result of my curiosity of a different, but slightly similar, symbol replacing the quotations.

  • Does the original author appear to have gotten some value out of performing the experiment?

–I believe he has gotten some value out of this experiment.

  • Any suggestions or observations that could improve this particular process (in general, or specifically you, or specifically for the original author).

– I don't think there are any suggestions, seems pretty straight forward.

Part 3

Entries

Entry 9: April 26, 2012

This is a sample format for a dated entry. Please substitute the actual date for “Month Day, Year”, and duplicate the level 4 heading to make additional entries.

As an aid, feel free to use the following questions to help you generate content for your entries:

  • On this day, I learned how to create nested functions to achieve a set goal.
  • It allowed me to complete a project, as well as showed me what is possible with functions.
  • I had trouble figuring out how to work pointer functions, due to the use of pointers inside of them and passing them to each other.
  • I understand it, now. The use of nested functions should be easier for me, now.

Entry 10: April 26, 2012

  • On this date, I found out that I can use fscanf instead of fgetc to accept character input that I need to change into integer.
  • This allows me to use something I am more familiar with to assign input to values.
  • What doesn't quite make sense to me is the buffer, and how if the buffer has a random value, like enter from the last time it was pressed, it gets printed.
  • The challenge I am facing with the course at the moment is catching up on all of my work!

Entry 11: April 5, 2012

  • On this date, we learned about polymorphism.
  • Polymorphism allows a program to redefine functions and use them for a different purpose.
  • The idea makes sense, what doesn't make as much sense is how to implement it in programming.
  • I am having trouble with C++ and most of what that includes.

Entry 12: April 22, 2012

  • On this date, we learned about Templates.
  • Templates are like blueprints of code. It contains something that can be made but isn't actually made in the template.
  • I'm not sure how I would use this, it seems that it would be important, but how to write it, I have no idea.
  • I think I will try to implement it a few times.

cprog Keywords

Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)
Namespaces [C++]
Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]
Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]
Inheritance (single, multiple Inheritance), Polymorphism/Virtual Functions, Abstract Base Class [C++]
Exception Handing (throw, try, catch) [C++]
Templates, STL (Standard Template Library) [C++]
Structures (Declaration, Accessing Elements, Pointers to)

cprog Keyword 17

Structures (Declaration, Accessing Elements, Pointers to)

Definition

Structures contain public variables held under one name. Each of these variables can be different data types. These variables are known as members.

Demonstration
/*
 *
 * Sample code block
 *
 */
 
#include<stdio.h>
 
int main()
{
        struct person{
                char *name;
                unsigned char age;
                short int weight;
                float gpa;
        };
 
        typedef struct person P;
        struct P p1, p2, p3, p4, p5;
 
        pl.age = 29;
        return(0);
}
cprog Keyword 18

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

Definition

A template is like a blueprint,

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

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

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

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

Definition

A class is similar to a struct. The main difference is that a class can hold both data and functions. Objects are created by using classes. Access control includes the use of the private, public, and protected keywords. They actually determine what can access the variables in the class. Public allows anyone to access those variables, private allows only the members of the same class to access those variables, and protected allows only members of the same class and their friends.

Demonstration

Demonstration of the chosen keyword.

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

/*
 * Sample code block
 */
#include <cstdio>
#include "num.h"
 
        class num {
                public:
                        num();
//                      ~num();
                        float average(int, int, int, int);
//                      int sum(int, int, int, int);
                        void set(int,int,int,int);
                        int get(int);
                private:
                        int n1,n2,n3,n4;
                  };
 
        num :: num()
        {
                n1=0;
                n2=0;
                n3=0;
                n4=0;
        }
 
        float num :: average(int a, int b, int c, int d)
        {
                return((float)(a+b+c+d)/4);
        }
 
 
        void num :: set(int a, int b, int c, int d)
        {
                n1=a;
                n2=b;
                n3=c;
                n4=d;
        }
 
        int num :: get(int value)
        {
                int result=0;
                switch(value)
                {
                        case 1:
                                result=n1;
                                break;
                        case 2:
                                result=n2;
                                break;
                        case 3:
                                result=n3;
                                break;
                        case 4:
                                result=n4;
                                break;
                        default:
                                result=-9999;
                                break;
                }
                return(result);
        }
 
 
int main()
{
        num myNum;
        myNum.set(7,0,0,0);
        return(0);
}
cprog Keyword 20

Exception Handling (throw, try, catch) [C++]

Definition

Exceptions, from what I have seen, appear to be a type of debugging that can occur during runtime. The program will run through a try block, and if the exception does not exist, then the program will continue running.

Demonstration

Demonstration of the chosen keyword.

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

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

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

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

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

Definition

Inheritance allows a program to reuse existing classes in different cases, without actually changing the values in the classes.

Demonstration

Demonstration of the chosen keyword.

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

The AND file:

#include "gate.h"
#include "and.h"
 
AND::AND()
{
        setA(false);
        setB(false);
        setX(false);
}
 
void AND::process()
{
        if((A==true) and (B==true))
                setX(true);
        else
                setX(false);
}

The NOT file:

#include "gate.h"
#include "not.h"
 
NOT::NOT()
{
        setA(false);
        setX(false);
}
 
void NOT::process()
{
        if(A == false)
                setX(true);
        else
                setX(false);
}

The OR file:

#include "gate.h"
#include "or.h"
 
OR::OR()
{
        setA(false);
        setB(false);
        setX(false);
}
 
void OR::process()
{
        if((A == false) and (B == false))
                setX(false);
        else
                setX(true);
}

The main file:

#include"gate.h"
#include"and.h"
#include"or.h"
#include"not.h"
#include<stdio.h>
 
int main()
{
        AND *myAND = new AND();
        myAND -> setA(true);
        myAND -> setB(false);
        myAND -> process();
        printf("Result of AND is: %d\n", myAND->getX());
 
        OR *yoOR = new OR();
        yoOR -> setA( true );
        yoOR -> setB( true );
        yoOR -> process();
        printf("Result of OR is: %d\n", yoOR -> getX());
 
        NOT *whyNOT = new NOT();
        whyNOT -> setA( false );
        whyNOT -> process();
        printf("Not A is: %d\n", whyNOT -> getX());
        return(0);
}

With the following header files, the C++ files can use the same class file:

The OR header file:

#ifndef _OR_H
#define _OR_H
 
class OR:public gate {
        public:
                OR();
                void process();
};
 
#endif

The AND header file:

#ifndef _AND_H
#define _AND_H
 
class AND:public gate {
        public:
                AND();
                void process();
};
 
#endif

The NOT header file:

#ifndef _NOT_H
#define _NOT_H
 
class NOT:public gate {
        public:
                NOT();
                void process();
};
 
#endif

The most important files of the code, the ones that hold the classes to allow inheritance, the gate.cc file and the gate.h file:

#include "gate.h"
 
gate :: gate()
{
        A=B=X=false;
}
 
//returns X
bool gate :: getX()
{
        return(X);
}
 
void gate :: setA(bool A)
{
        this->A=A; // 'this.' allows you to reference yourself.'this.A' is
                  // the A in the protected part of the class.
}
 
void gate :: setB(bool B)
{
        this->B=B;
}
 
void gate :: setX(bool X)
{
        this->X=X;
}
#ifndef _GATE_H
#define _GATE_H
 
class gate {
        public:
                gate();
                bool getX();// LOOK UP BOOL DATA TYPE!!!!
                void setA(bool);
                void setB(bool);
        protected:
                void setX(bool);
                bool A;
                bool B;
        private:
                bool X;
};
 
#endif
cprog Keyword 22

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

Definition

The compiler turns source code into executable code. The preprocessor takes data that is input into a compiler and returns output that can be used in another program. Multi-file programs take separate files and, when compiled together, take data from each file and run a program.

Demonstration
 
cprog Keyword 23

Namespaces [C++]

Definition

Namespaces allow programs to group classes and objects together and be used under different names.

Demonstration

Demonstration of the chosen keyword.

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

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

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

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

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

Definition

Type casting allows a program to assign a variable of one data type equal to a variable of another data type, and then forces that value to be the new data type. Type casting operators consist of dynamic_cast, static_cast, reinterpret_cast, const_cast, and typeid. Const-Volatility Specifiers set types as whichever you choose. Const sets the type to const, and volatile set the type to volatile.

Demonstration

Demonstration:

 

cprog Objective

cprog Objective

Distinguish and explain difference between homogeneous and heterogeneous composite data types:

Definition

Homogeneous composite data types consist of created variables with multiple spaces of memory that can either be empty or filled, that are of the same data type. Heterogeneous composite data types consist of very similar variables, except they hold multiple data types.

Method

Some of the various data types that are capable of holding more than one value or space of memory are:

  • struct
  • arrays
  • classes
  • unions

What determines whether or not they are heterogeneous or homogeneous is whether or not they have more than one data type stored in them.

Measurement

Most arrays are of one data type, which is defined when the array is initialized:

   char *array[10];

Unions and Structs are very similar, and they both can have more than one data type. They are seen more often as the group of code that would have more than one data type stored in them.

This is a Union:

        union var {
                int x;
                float f;
        };

What is special about a union is that it holds one block of memory for multiple values. Each time a variable is assigned a value in the code, the old value in the memory is replaced with the new.

Struct:

        struct person{
                char *name;
                unsigned char age;
                short int weight;
                float gpa;
        };

A struct can have more than one block of memory, one for each of the values in the struct.

Analysis

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

  • How did you do?

– From what I was able to type up, it seems that my understanding of it now is pretty good.

  • Is there room for improvement?

– There is room for improvement, I still have a little trouble with creating these and implementing them, but with a little practice, I should be fine.

  • Could the measurement process be enhanced to be more effective?

– It could be, I could have implemented code and shown the result.

  • Do you think this enhancement would be efficient to employ?

– It would be efficient to employ, it would help me understand these concepts more.

  • Could the course objective be altered to be more applicable? How would you alter it?

– It probably could be, in the way that I mentioned.

Experiments

Experiment 7

Question

Will passing by reference work just as well as passing by value? Specifically, would they give me the same result?

Resources

Passing by reference is a method that, when looking at pointers, points one argument at the address of another. Passing by value allows the compiler to copy one or more values in one or more addresses into a function, and allows the function to use these values. The original variables that are used are not changed.

Hypothesis

I believe that they won't give me the same result. What will most likely happen is using pass-by-reference will allow me to manipulate the value given and the value given will be saved, but the value will not be saved as I would have liked with pass-by-value.

Experiment

In my experiment, I will create a running program that will use both methods for the same purpose. The program will have one function for performing passing-by-value; the main function will have the coding for passing-by-reference. I will perform the same change on the variables, and that will determine whether or not the same change takes place for both cases.

Data

Perform your experiment, and collect/document the results here.

Code for the experiment:

#include <stdio.h>
#include <stdlib.h>
 
// Function to demonstrate passing-by-value
 
void passByValue( int val1, int val2 )
{
        int pbv1, pbv2;
        pbv1 = pbv1 + 5;
        pbv2 = pbv2 + 5;
}
 
int main()
{
        int pbv1 = 5, pbv2 = 10, pbr1 = 5, pbr2 = 10;
        printf("Values before adding 5:\n");
        printf("a: %d\nb: %d\nc: %d\nd: %d\n", pbv1, pbv2, pbr1, pbr2);
 
        passByValue( pbv1, pbv2 );
        pbr1 = pbr1 + 5;
        pbr2 = pbr2 + 5;
 
        printf("Values after adding 5:\n");
        printf("a: %d\nb: %d\nc: %d\nd: %d\n", pbv1, pbv2, pbr1, pbr2);
        return 0;
}

Results of the experiment:

lab46:~/src/cprog/Opus/Opus3$ ./experiment1 
Values before adding 5:
a: 5
b: 10
c: 5
d: 10
Values after adding 5:
a: 5
b: 10
c: 10
d: 15
lab46:~/src/cprog/Opus/Opus3$ 

Analysis

Based on the data collected:

  • Was your hypothesis correct?

– My hypothesis was correct, they did not have the same change in values.

  • Was your hypothesis not applicable?

– My hypothesis was applicable, the variables that were passed by reference did change, but the variables that were passed by value did not remain changed, they went back to their original values.

  • Is there more going on than you originally thought? (shortcomings in hypothesis)

– Not really, all that I thought would happen, did happen. This just helped me to confirm my understanding of passing variables in different ways.

  • What shortcomings might there be in your experiment?

– I did not print what the value was in the function, so the value may have never changed. I am certain that it did, however.

  • What shortcomings might there be in your data?

– There weren't any, really. Everything seemed to work and was accounted for.

Conclusions

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

– I can now say that I fully understand the difference between passing-by-value and passing-by-reference. I was confused on what the differences were, and if they were both applicable in any case, but it seems that they aren't and I need to decide when either is more appropriate.

Experiment 8

Question

When using logic operators, can one use more than two (in an if statement)?

Resources

Logic operators consist of and, or, not, is equal to, etc. These logic operators are usually used to check one variable or compare two variables which determine whether or not a piece of code will run or not. These operators are represented, in code, by these characters:

  • and: &&
  • or: ||
  • not or not equal to: !=
  • is equal to: ==

Hypothesis

I don't think that more than two logic operators can be used without any clarification of their separation (parenthesis separating them). I believe that this would cause confusion in the code, and the compiler would not read the code as it was intended to be read, therefore leading to a logical error, but not a syntax error.

Experiment

I am going to create a block of code that will test this. The if block will only run if x and y are greater than 0 or less than 0.

Data

Code for the experiment (the one that separates):

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        int x = 0, y = 0;
 
        printf("The following program will test to see if the result of two input numbers, when multiplied or divided, \
\nwill return a positive or negative number.\nPlease input the first value: ");
        scanf("%d", &x);
        printf("\nPlease input the second value: ");
        scanf("%d", &y);
 
        if( x == 0 || y == 0 )
        {
                printf("The value is zero.\n");
        }
        else if( ( x > 0 && y > 0 ) || ( x < 0 && y < 0 ) )
        {
                printf("The value will be positive\n");
        }
        else
        {
                printf("The value will be negative\n");
        }
        return 0;
}

The result for this code (with parenthesis as separation) worked and printed this:

lab46:~/src/cprog/Opus/Opus3$ ./experiment2
The following program will test to see if the result of two input numbers, when multiplied or divided, 
will return a positive or negative number.
Please input the first value: -1

Please input the second value: -2
The value will be positive
lab46:~/src/cprog/Opus/Opus3$ ./experiment2
The following program will test to see if the result of two input numbers, when multiplied or divided, 
will return a positive or negative number.
Please input the first value: 1

Please input the second value: 2
The value will be positive
lab46:~/src/cprog/Opus/Opus3$ ./experiment2
The following program will test to see if the result of two input numbers, when multiplied or divided, 
will return a positive or negative number.
Please input the first value: -1

Please input the second value: 2
The value will be negative
lab46:~/src/cprog/Opus/Opus3$ ./experiment2
The following program will test to see if the result of two input numbers, when multiplied or divided, 
will return a positive or negative number.
Please input the first value: 1

Please input the second value: -2
The value will be negative
lab46:~/src/cprog/Opus/Opus3$ 

Code without separation:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        int x = 0, y = 0;
 
        printf("The following program will test to see if the result of two input numbers, when multiplied or divided, \
\nwill return a positive or negative number.\nPlease input the first value: ");
        scanf("%d", &x);
        printf("\nPlease input the second value: ");
        scanf("%d", &y);
 
        if( x == 0 || y == 0 )
        {
                printf("The value is zero.\n");
        }
        else if( x > 0 && y > 0 || x < 0 && y < 0 )
        {
                printf("The value will be positive\n");
        }
        else
        {
                printf("The value will be negative\n");
        }
        return 0;
}

The result without separation:

lab46:~/src/cprog/Opus/Opus3$ ./experiment2
The following program will test to see if the result of two input numbers, when multiplied or divided, 
will return a positive or negative number.
Please input the first value: 1

Please input the second value: 1
The value will be positive
lab46:~/src/cprog/Opus/Opus3$ ./experiment2
The following program will test to see if the result of two input numbers, when multiplied or divided, 
will return a positive or negative number.
Please input the first value: -1 

Please input the second value: -1
The value will be positive
lab46:~/src/cprog/Opus/Opus3$ ./experiment2
The following program will test to see if the result of two input numbers, when multiplied or divided, 
will return a positive or negative number.
Please input the first value: 0

Analysis

Based on the data collected:

  • Was your hypothesis correct?

– My hypothesis was incorrect. I should have known, seeing as how C programming is free-form.

  • Was your hypothesis not applicable?

– It wasn't really applicable, I figured it out, and decided to double check my incorrectness-ocity-ism!

  • Is there more going on than you originally thought? (shortcomings in hypothesis)

– Not really with this, it is a simple concept, I just messed up!

  • What shortcomings might there be in your experiment?

– Well, at first, I had an error. I fixed it in the code and it ran properly.

  • What shortcomings might there be in your data?

– There don't appear to be any shortcomings in my data.

Conclusions

Well, my understanding of how free-form coding works seems to have eluded me for a time. I have regained it, and now I shall use that power to further my exploration into the world of programming! YEAH!

Retest 3

Perform the following steps:

State Experiment

Whose existing experiment are you going to retest? Provide the URL, note the author, and restate their question.

– I decided to retest Josh Davis' experiment about multiplying an int value and a float value together. What would be the result?

http://lab46.corning-cc.edu/opus/spring2012/jdavis34/start#experiment_3

Resources

Evaluate their resources and commentary. Answer the following questions:

  • Do you feel the given resources are adequate in providing sufficient background information?

– He said he was able to create and run the program to provide a result for this experiment on his own from what he had learned in class. I believe it. He seemed to know what he was doing.

  • Are there additional resources you've found that you can add to the resources list?

– I would use the C for Engineers class as a resource, because I vaguely remember learning about this, the answer just escapes me.

  • Does the original experimenter appear to have obtained a necessary fundamental understanding of the concepts leading up to their stated experiment?

– I believe he does understand it.

  • If you find a deviation in opinion, state why you think this might exist.

– No deviations in opinion, sir!

Hypothesis

State their experiment's hypothesis. Answer the following questions:

  • Do you feel their hypothesis is adequate in capturing the essence of what they're trying to discover?

– I believe that he has a thorough hypothesis, but I don't think it will go as he plans it to.

  • What improvements could you make to their hypothesis, if any?

– I don't think that there are any improvements that you could make on his hypothesis. It seems very in depth.

Experiment

Follow the steps given to recreate the original experiment. Answer the following questions:

  • Are the instructions correct in successfully achieving the results?

– The instructions appear to be correct.

  • Is there room for improvement in the experiment instructions/description? What suggestions would you make?

– I would suggest that he should have given some sort of result, and spaced it all out, made it a little easier to read. Just small things.

  • Would you make any alterations to the structure of the experiment to yield better results? What, and why?

– I would not!

Data

Publish the data you have gained from your performing of the experiment here.

DA CODE:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
        float x, z1;
        int y, z2;
 
        printf("Please input a number with a decimal value: ");
        scanf("%f", &x);
 
        printf("\nPlease input a whole number: ");
        scanf("%d", &y);
 
        z1 = x * y;
        z2 = x * y;
 
        printf("\nThe result stored in a float variable: %f\n", z1);
        printf("The result stored in an int variable: %d\n", z2);
 
        return 0;
}

DA RESULT:

lab46:~/src/cprog/Opus/Opus3$ ./retest2
Please input a number with a decimal value: 1.2

Please input a whole number: 2

The result stored in a float variable: 2.400000
The result stored in an int variable: 2
lab46:~/src/cprog/Opus/Opus3$ 

Analysis

Answer the following:

  • Does the data seem in-line with the published data from the original author?

– It is hard to determine, because he never actually showed any results. He used a function he created to multiply them together, which is cool, but I didn't do that.

  • Can you explain any deviations?

– Mine was a little more organized and seemed to work better, since he said his did not compile.

  • How about any sources of error?

– There are no errors in mine.

  • Is the stated hypothesis adequate?

– The stated hypothesis is pretty good, had I not known ahead of time, I would have thought the same thing would happen.

Conclusions

Answer the following:

  • What conclusions can you make based on performing the experiment?

– I can conclude that it is not necessary to add a specifier of how many decimals is needed when printing out a float value or assigning a float value.

  • Do you feel the experiment was adequate in obtaining a further understanding of a concept?

– I do believe that this experiment was a good way of further understanding floats, since we didn't work with them much during the course.

  • Does the original author appear to have gotten some value out of performing the experiment?

– It appears that he knew, then, that his understanding of variables and data types was not complete and not as in depth as he thought.

  • Any suggestions or observations that could improve this particular process (in general, or specifically you, or specifically for the original author).

– I have no suggestions.

opus/spring2012/jcavalu3/start.txt · Last modified: 2012/08/19 16:24 by 127.0.0.1