User Tools

Site Tools


opus:spring2012:brobbin4:part1

Part 1

Entries

Entry 1: February 3, 2012

Today we made progress with the online assignments that are due for my UNIX/Linux Fundamentals class. As part of one of the assignments we had to draw an ASCII file tree that showed our home directory within the UNIX directory structure. we also had to show 3 folders and 3 files that are contained within our home directory. Below is the finished image I created.

Entry 2: February 5, 2012

Well the first two weeks of classes are down and already I have learned so much about the C programming language. We have already written and compiled a few simple programs and it definitely been a fun learning experience. So far in class we have been focusing on the base structure of C programming, working with “printf” and “scanf” functions along with memory allocation (malloc) and learning how to use pointers in programming. All of these are siginificant because it is the basis of the programming. Without this knowledge a person cannot properely write code and expect it to compile and work with no issues. This information is also significant because it will also be used heavly utilized durring the progression of the course. This will definitely be the most challenging course that I have taken to date due to the fact that I have never taken a programming course, so this is definitely going to be an interesting semester.

  • The most significant thing learned to date would be pointers.
  • Pointers are very siginificant because they allow us to accomplish many tasks within a program while reducing the overall ammount of code that is required to make the program function properly.
  • Through the use of pointers you can have several processes access and control the information that is stored in one particular memory address instead of having to allocate more memory to perform a task.

Entry 3: February 9, 2012

Just completed the puzzlebox challenge for my UNIX/Linux class. The first parts I thought were pretty easy. I had to figure out the file type using the “file” command in Linux and then change the filenames so I could uncompress the files using various tools such as gzip and zip. The last part was pure evil for me and took me the better part of 2 days to figure out. The message was backwards and had a bunch of erroneous characters within it that had to be removed. I used a combination of the “sed” and “rev” commands to finally decrypt the message.

  • Today I learned how to identify files in UNIX/Linux with the “file” command.
  • This is significant because a user cannot rely on file extensions alone to determine what kind of file they are dealing with.
  • So far all of the concepts that I am learning in class are making sense due to my previous experiences with the UNIX/Linux operating system
  • So far the only challenge I have been faced with was the puzzlebox challenge that I just completed, mostly because I have never had any experience with the “sed” and “rev” commands.

Entry 4: February 16, 2012

Today was a challenging day in my C/C++ class. We were asked to write a program that encompassed all of the things that we have learned to date. The program had to accept command line arguments, prompt a user for a number between 0 and 4, and have data stored in a 2d array that could be called on by the selected numerical option. This was challenging simply because I have never wrote any code before. After writing the program and getting a helper or two from my instructor and classmates I finally understood how 2d arrays worked in C and I also learned the proper syntax for a while loop when using the loop to verify more then one rule.

Entry 5: February 23, 2012

Wow, what a week! Coming back from a mini break a the second project of the semester is coming due in my C/C++ class. I have already learned that I shouldn't wait until its almost due before I do the work as I sit here pounding my head against my desk. The program I have to create needs to cipher a message using a key that is provided either as a command line argument or is provided in an external text file. The message to be ciphered needs to be read from a test file and the new, ciphered message, needs to be wrote to a new text file. The hardest part of this entire program is figuring out the process that needs to occur and what statements need to be used to properly cipher the message. As this is not already hard enough a second program needs to be created that can decipher the ciphered message using the same key file or by providing the same key as a command line argument like the cipher program. Good thing its not due until tomorrow evening, I still have some time to get help on this from the IRC, lol.

Entry 6: February 25, 2012

Thank god! My instructor had mercy on our souls during this current project and has graciously extended our due date by another day. On top of that he has provided us with a hint as to what needs to be included in our code to make the programs work. Well after looking at the hint and implementing it into my program I still had issues. The message would cipher, but not correctly. The program was not ciphering by the key contained within the key file. The IRC was my biggest savior this time. After bouncing ideas back and forth with a fellow classmate I was finally able to get my programs to work properly. The hint was to make the program convert all characters within the message to there ASCII values, then cipher them with the key by adding the key to the ASCII value and then writing that value to a new file in its character form. The decipher program basically did the same thing but only the math in the program was reversed. Where you added in the cipher program, you subtracted in the decipher program. The issue with the key file turned out to be a simple statement make the program accept the numerical key from the file when performing the ciphering and deciphering equations. Finally my programs and the project are done and I can sleep a little easier tonight.

Entry 7: February 28, 2012

Today in class we dove into functions and wrote a small program that utilized a few different functions. The program would take a two command line arguments, the first would tell how many iterations of the program would run, then the second would determine the threshold of the resulting answers. Then the program would perform modular division using the second argument and a seed from srand. As long as the quotient is below the threshold the program would determine wether the answer was even or odd and then output the results on stdout. This was a new and interesting because I learned how functions actually work and how they are utilized witin a program, how to pump information into a function and get something meaningful in return. Before I started this class I thought I didn't neew any programming expreience because I didn't want to become a programmer, but now I am happy I have the change to learn about this because it's not only interesting, but it's something I can use later.

Entry 8: March 2, 2012

Working on finishing up the first part of this opus as it is due tonight at midnight. Thus far I have really learned alot between both classes, but more so in the C / C++ programming class. Its definatelly interesting and something I can use. I have also realized why Matt wants all students to create an opus. It allows us to not only keep a record of what we have learned but also allows us to show off our new found knowledge through the experiments that we do. To me this also seems like a great piece of work that could be added to a resume to allow a potential employer see what has been learned while earning your degree.

Keywords

cprog Keywords

Pointers

Definition

A pointer is a special type of variable in the C programming language that holds the memory address of another variable. The anatomy of a pointer is broken down into three parts, the address of, the assignment, and the dereferencing. First comes the addressing of the pointer. At this stage a pointer is defined within the programming language but currently doen not point to anything. Next comes the assignment of the pointer. In this stage the pointer is is referenced, or given a value to point at in memory. Last comes the dereferencing of the pointer. In this last stage the pointer is called on within the programming code. Because a pointer points to a value in memory, the value is being pointed to is either read out or written too depending on the operation that is taking place.

Demonstration

Below is a sample code of a pointer as found in the C programming language:

Note: A pointer is defined with a astrix before its name. The ampersand before “test” means “address of”, so we have basically said the pointer “link” points to the memory address of “data”.

/*
 * Sample code for a pointer
 */
#include <stdio.h>
 
int main()
{
    int data
    int *link; //On this line the pointer "link" is defined.
 
    *link = &data; //On this line we have set the "link' pointer to "point" to the information stored in "data".
    printf("The integer named "data" contains the value %hhu\n", data);
    printf("The pointer named "link" contains the value %hhu\n", *link);
 
    return(0);

Below is the resulting output of the above code once compiled:

lab46:~$ ./test
The integer named data contains the value 42
The pointer named link contains the value 42
lab46:~$

Header Files

Definition

A “header file” is a file that contains specific elements of a programs code such as commonly used declarations, variables, and other commonly used code into a packaged that is easily distributed and are reusable in other works. Commonly used header files include “stdio.h” which defines a systems standard input and output devices such as the monitor and keyboard, and “stdlib.h” which is a systems general utilities library and handels things like dynamic memory management and random number generation.

Demonstration

Below is a sample of header files being used within the code of a program.

/*
 * Sample code block
 */
#include <stdio.h> // On this line we are including the library "stdio.h" ("stdio" stands for "standard input/output")
#include <stdlib.h> // On this line we are including the library "stdlib.h" ("stdlih" stands for "standard library")
 
int main()
{
    char = *word
    word=(char*)malloc(sizeof(char)*24);
    return(0);
}

Standard I/O (STDIO, STDOUT, STDERR)

Definition

Input and output are absoutely necessary in a computer based world. If a computer has no input it has no purpose, and without an output we are unable to tell what the computer has done with the data we fed to it. But what if there is a problem, the computer needs a way to deal with a problem or error within the data that it has been fed. There exists a library, the C Standard Input and Output Library, known as stdio.h in the C language that contains all the necessary information a computer needs to interface with any standard input and output device. This library contains three standard streams, stdin, stdout, and stderr. Stdin handles input such as your keyboard and mouse. Stdout handles output to devices such as a monitor or printer. Stderr handles any error that may occurs and outputs an error message to the standard output device which is normally the monitor. These streams are automatically created and opened for any programs that access the library.

Demonstration

Below is an exmaple of Standard I/O as used in the C language.

/*
 * Sample code block
 */
#include<stdio.h> // This is where the C Standard Input/Output Library is introduced into the program code.
#include<stdlib.h>
 
int main()
{
        int datain=0, *dataout;
        dataout = &datain;
        printf("Please enter a number that is 0 or greater.");
        fscanf(stdin, "%d", &datain); // On this line the program accepts an input from a standard input device, most commonly the keyboard.
        while( datain < 0 )
        {
                fprintf(stderr, "You entered a number less than 0. Try again."); // This line tells the program to output an error message when an invalid value is given. Normally this error is directed to another file but in this case it has been redirected to the screen through the use of the fprintf statement.
                printf("\n");
                printf("\n");
                printf("Please enter a number that is 0 or greater.");
                fscanf(stdin, "%d", &datain);
                printf("\n");
        }
        printf("Your number is %d\n", *dataout); // Here the program outputs a result to the standard output device, most commonly the monitor.
        printf("\n");
        return(0);
}

Below is the output of the above code once compiled and executed:

lab46:~$ ./test
Please enter a number that is 0 or greater.0
Your number is 0

lab46:~$ ./test
Please enter a number that is 0 or greater.-1
You entered a number less than 0. Try again.

Please enter a number that is 0 or greater.1

Your number is 1

lab46:~$

Repetition/Iteration Structures (for, while, do while)

Definition

Repetition/Iteration structures are essential in the C programming language. These structures allow for a program to do multiple things without having to be restarted for each new process. There are 3 different types of structures, for, while, and do while, and each of these structures have a different purpose. A “for loop” will loop from one integer to the next while incrementing by specified ammount. A “while loop” can be used to run a process repetitively when the number of times a loop need to run is not known. A “do while loop” is almost the same as a while loop with one exception. After the loop has run once it will test the data to see if we have to continue or end the loop.

Demonstration

Below is an example of a repetition/iteration structure as found in the C programming language.

/*
 * Sample code block
 */
#include<stdio.h>
#include<stdlib.h>
 
int main()
{
        int datain=0, *dataout;
        dataout = &datain;
        printf("Please enter a number that is 0 or greater.");
        fscanf(stdin, "%d", &datain);
        while( datain < 0 ) // this is the beginning of the iteration structure. This iteration structure is a while loop and is designed to loop untill the proper input is given.
        {
                printf("You entered a number less than 0. Try again.");
                printf("\n");
                printf("\n");
                printf("Please enter a number that is 0 or greater.");
                fscanf(stdin, "%d", &datain);
                printf("\n");
        }
        printf("Your number is %d\n", *dataout);
        printf("\n");
        return(0);
}

Below is the output of the above code once compiled and ran:

lab46:~$ ./test
Please enter a number that is 0 or greater.0
Your number is 0

lab46:~$ ./test
Please enter a number that is 0 or greater.-1
You entered a number less than 0. Try again.

Please enter a number that is 0 or greater.1

Your number is 1

lab46:~$

File Access

Definition

File access in the C programming is the act of a program accessing a file for the purpose of reading the contents of a file, writing data to a new or existing file, or appending data to an existing file.

Demonstration

Below is an example of File access in the C programming language.

#include<stdio.h>
#include<stdlib.h>
 
int main()
 
{
        FILE *in,*out; // Here two file pointers are defined named in and out.
        char value=0;
        in=fopen("file.txt","r"); // Here the file "file.txt" is opened with read permissions.
        out=fopen("out.txt","w"); // Here the file "out.txt" is opened with write permissions.
        if(in==NULL)
        {
                printf("ERROR!\n");
                exit(1);
        }
        fscanf(in,"%hhd",&value);
        while(value!=-1)
        {
                value*=2;
                fprintf(out,"%hhd\n",value); // Here the program writes data to the file "out.txt" via the file pointer "out".
                fscanf(in,"%hhd",&value); // Here the program reads data from the file "file.txt" via the file pointer "in".
        }
        fclose(in); // Here the file "file.txt" is closed via the file pointer "in".
        fclose(out); // Here the file "out.txt" is closed via the file pointer "out".
        return(0);
}

Functions, Parameters

Definition

A function in the C programming language is a block of code that has a name and property that are reusable. This means that a function can be called on from as many different points in the program as needed.

A Parameter in the C programming language is any data that is passed to a function.

Demonstration

Below is an example of functions and parameters as found in the C programming language.

#include<stdio.h>
#include<stdlib.h>
 
int sum(int, int, int, int); //This is a function prototype for sum
 
float avg(int, int, int, int); //This is a function prototype for average
 
int main() // This is the "main" function of the program. "Main" defines what the program will actually accomplish when executed.
 
{
        int a=0, b=0, c=0, d=0, max=0, min=0;
 
        printf("Enter first value");
        fscanf(stdin, "%d", &a);
 
        if(a > max)
        {
                max=a;
        }
 
        printf("Enter second value");
        fscanf(stdin, "%d", &b);
 
        if(b > max)
        {
                max=b;
        }
 
        printf("Ented third value");
        fscanf(stdin, "%d", &c);
 
        if(c > max)
        {
                max=c;
        }
 
        printf("Enter fourth value");
        fscanf(stdin, "%d", &d);
 
        if(d > max)
        {
                max=d;
        }
 
        if((a < b)&&(a < c)&&(a < d))
        {
                min=a;
        }
 
        if((b < a)&&(b < c)&&(b < d))
        {
                min=b;
        }
 
        if((c < a)&&(c < b)&&(c < d))
        {
                min=c;
        }
 
        if((d < a)&&(d < b)&&(d < c))
        {
                min=d;
        }
 
        fprintf(stdout, "The sum of %d, %d, %d, and %d is %d\n", a,b,c,d,sum(a,b,c,d));
 
        fprintf(stdout, "The average of %d, %d, %d, and %d is %f\n", a,b,c,d,avg(a,b,c,d));
 
        fprintf(stdout, "The highest value entered is %d\n", max);
 
        fprintf(stdout, "The smallest value entered is %d\n", min);
 
        return(0);
}
 
int sum(int n1, int n2, int n3, int n4) // Here a function named "sum" is defined and the integer parameters n1, n2, n3, and n4 are passed to it. 
 
{
        int total=0;
        total=n1+n2+n3+n4;
        return(total);
}
 
float avg(int n1, int n2, int n3, int n4) // Here another function named "avg" is defined and the integer parameters n1, n2, n3, and n4 are passed to it.
 
{
        float total=0;
        total=(float)(n1+n2+n3+n4)/(4);
        return(total);
}

Arrays

Definition

An array is a collection of memory addresses that all store the same data type of and can be referenced through a common variable name. An array must be declared before they can be used in a program.

Standard notation is the standard syntax used within the C programming language to create or access an array.

Pointer Arithmetic is the method used to access an element or elements of an array.

There are two types of arrays that exist, single-dimensional and multi-dimensional. A single-dimensional array is an array that is organized into one single row or column. A multi-dimensional array is an array that is organized into multiple rows or columns.

Demonstration

Below is an example of arrays as found in the C programming language.

#include<stdio.h>
#include<stdlib.h>
 
int main(int argc, char **argv) // Here **argv is defining a multi-dimensional array. This array is fed from arguments that are entered at the time of the programs execution. 
{
        int datain;
        unsigned char i;
 
        printf("Please enter a value between 0 and 4");
        fscanf(stdin, "%d", &datain);
        while( datain < 0 || datain > 4) 
        {
                printf("You entered a value that is not between 0 and 4. Please try again");
                printf("\n");
                printf("Please enter a value between 0 and 4");
                fscanf(stdin, "%d", &datain);
        }
        for(i=0; i < argc; i++)
        {
                printf("argv[%hhu]: %c\n", i, *(*(argv+i)+datain)); // Here the array is de-referenced through the use of pointer arithmetic and an array element is read based on the result from the arithmetic. Note how the array is referenced as this is the standard notation for working with arrays.
        }
        return(0);
}

Variables

Definition

Within the C programming language, a variable is a name that is used to refer to a specific point in memory. There are four different types of variables which are int, char, float, and double.

The “int” variable type is used to store integers that are in the form of whole numbers. On a 32 bit computer system an “int” is 32 bits or 32/8 which is 4 bytes length. This means that an “int” has the possibility of storing one of 4294967296 different possibilities.

The “char” variable is capable of holding any member of the character execution set. A char can hold the same kind of data that an “int” can but a char is normally 8 bits or 8/8 which is 1 byte in length.

The “float” variable, short for “floating point” is used to store real numbers. A “float” is only the size of one machine word size which on todays system is typically 32 bits or 32/8 which is 4 bytes in length.

The “double” variable, short for “double floating point” is similar to a normal “float”. While a “float” only allows for the storage of integers a “double” allows for the storage of both integer and non-integer data. The reason its called a “double” is due to the fact that it is double the size of a “float” which makes it 64 bits or 64/8 which is 8 bytes in length.

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()
{
    int num=8; // Here an "int" variable is declared and is initialized with the integer number 8.
    char i; // Here a "char" variable named "i" is declared.
    float data; // Here a "float" variable named "data" is declared.
    double input=2x; // Here a "double" variable named "input" is declared and it initialised with a value of 2x.
    return(0);
}

cprog Objective

cprog Objective

The objective of this course is to learn both the C and C++ programming languages and how to properely utilize them.

Definition

This objective entials that a working knowledge of the C and C++ languages will be gained. This includes understading the languges and there proper syntax which includes the usage of pointers and variables, if/then/else statements, memory management, how to compile source code composed of C or C++ language.

Method

Successfull completion of this objective means that I would be able to look at any source code that is written in C or C++ and be able to understand what the program is accomplishing.

Measurement

Due to the current stage of completion of this course I cannot yet measure this accurately. While I have learned a great deal thus far I am still not at a level where I could say that I have met all of the course objective.

Analysis

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

  • At this point in time I do believe I am progressing at a good pace.
  • I do believe there is room for improvement but this inprovement will occur with further progression within the course.
  • Yes, the measurement could be enhanced to further reflect on many different parts of the course obective.
  • I do think this enhancement would be effective to employ and I will be employing this enhancement durring the progression of the course.

unix Keywords

Local Host

Definition

A “local host” is the local computer that a user is operating. A “local host” is also the standard name given to the loopback IP address of the network interface of a computer. This “local host” address is the address a computer can use to refer to itself when doing anything network or internet related.

Remote Host

Definition

A “remote host” is the term used to decsribe a remote system that users can connect to. Examples of a “remote host” would include webserver, file server or any system that allows remote client to connect to it.

Home Directory

Definition

The “home directory” is the directory for a particular user on a multi-user operating system. This directory contains all of the users settings and any files the particular user created.

Current Working Directory

Definition

The “current working directory” is the directory the user is currently residing in. A user can change there “current working directory” by issuing the “cd” or change directory command at the Linux command prompt.

Demonstration

Below is a sample that shows the “current working directory” and how to change the “current working directory”:

lab46:~$                   // This line shows that the current working directory is the home directory which is denotated by the "~" symbol.
lab46:~$ cd src            // This line shows the "cd" command being used and the directory name the user wants to switch to that is inside the home directory.
lab46:~/src$               // This line shows the result of the "cd" command that was issued. Note how the prompt has changed to show the new current working directory and its location to the home directory.

Types of Files

Definition

The Unix / Linux operating systems have 3 types of files which are, directory, regular, special.

The “directory” file type is a type of file that contains a list of other files and directories within it. these files are denotated with a “d” when a long directory listing is done.

The “regular” file type is the most common file type. These are the kinds of files that contain user data such as programs, documents, audio/video files, etc. these files are denotated by a hyphen when a long directoty listing is done.

The “special” file type encomapsses all other files that are not classified under the “directory” or “regular” types. These files include symbolic links which is denotated by an “l” when doing a long directory listing, a character deivce denotated by a “c”, a block device denotated by a “b”, etc.

Demonstration

Below is an example of the different file types found, note the information in the long directory listing.

system:/dev$ ls -l
crw------- 1 root root  10, 231 Jan 17 15:39 snapshot  //This is a character device which is a special file type, note the "c" designation for the character device file type.
drwxr-xr-x 2 root root       60 Jan 17 15:39 snd       //This is a "directory" file type, note the "d" designation for the file type.
lrwxrwxrwx 1 root root       24 Jan 17 15:39 sndstat -> /proc/asound/oss/sndstat  //This a also a special file type called a symbolic link, note the "l" designation for the file type.
-rw-r--r-- 1 user user      485 Feb 16 21:45 test.c    //This is a "regular" file type, note the "-" designation for the file type.
system:/dev$

The Unix Shell

Definition

The Unix Shell is the command line inteperter for Unix and Unix-like operating systems. This shell provides the user with a command line driven interface for the operating system. From this interface a user can execute programs, perform file manipulation and more. The Shell is also a scripting programming language for these operating system. Common operations performed with shell script include file manipulation, the execution of programs, and printing text.

Demonstration

Below is an example of the Unix Shell interface.

lab46:~$ cp test.c ~/script/test.c // Here file manipulation is occuring, the file test.c is being copied into the folder named "script" and is being named "test.c".
lab46:-$

Shell Scripting

Definition

Shell scripting is a programming language for the shell environment. Unline some programming languages this is a high level programming language. Shell scripts are most useful for program automation or when several programs need to be ran over and over. Instead of a user having to enter the commands over and over a script file can be created with the commands that are needed and then only the single script file needs to be executed, and in turn, the script will be read by the command interperter and the commands will be executed.

Demonstration

Below is an example of a Unix shell script. The script below will execute the mount command and mount a cd that is inserted in a cdrom drive at the mount point “/mnt/cdrom”. Then the script will then execute the cp command and copy the contents of the cdrom to a folder named “files” in the root directory. The the “tar” command is executed and the files located in the file/ directory are copied into an archive named “cdrom.tar”. Lastly the gzip command executes and conpressed the cdrom.tar archive.

/*
 * Sample Shell Script Code
 */
#!/bin/bash
mount /dev/cdrom /mnt/cdrom
cp /mnt/cdrom/file1*.* /files/
tar -cf cdrom.tar /files/*.*
gzip cdrom.tar

File Manipulation

Definition

File manipulation is the process of accessing a file or files for the purpose of performing some action upon them. These actions include but are not limited to reading the contents of a file, writing data to a file, deleting a file, changing the permissions on a file, etc.

Demonstration

Below is an example of file manipulation.

lab46:~$ cp file1 file2.txt                   //Here file manipulation occurs in the form of a file copy. The contents of file1 are being copied into a file named "file2.txt".
lab46:~$ rm file1                             //Here file manipulation occurs in the form of the deletion of the file named file1.
lab46:~$ echo "Hello World!" > file3.txt      //Here file manipulation occurs in the form of file creation and a file write procedure. The output of the echo command is piped into a file named "file3.txt". If this file didn't exist before, the file is created and then the output is written to the file.
lab46:~$ cat file3.txt                        //Here file manipulation occurs in the form of a file read. The file "file3.txt" is being read out and the contents are printed on the standard output device.
Hello World!
lab46:~/src$ 

unix Objective

unix Objective

The objective of this course is to gain a working knowledge of the Unix / Linux operating systems. This includes file manipulation, package management, shell scripting, desktop environments, etc.

Definition

This objective entails a systematic learning experience of the different parts of the Unix / Linux operating system from very basics such as file manipulation, to more advnace techniques such as shell scripting, which is the creation of scripts to automate certiant processes within the Unix / Linux operating system.

Method

By completing the labs and case studies associated with the course and by reading the text for the course and applying that knowledge to the course work I shall gain a mountain of knowledge of the Unix / Linux operating systems.

Measurement

Successfull completion of this course would entail gaining a working knowledge of the information gathered from the course and being able to demonstrate the knowleged that was obtained from the text and prior coursework.

Analysis

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

  • So far I believe I am progressing at a good pace.
  • There is always room for inprovement due to the fact that there is always more to learn.
  • I do not believe the process could be improved. The only way to really learn is by doing, so by doing the associated work I will learn the new information.
  • I do not believe the course objective could be altered. This course is about Unix / Linux, which means I will be learning about these operating systems which I believe my statement of the course objective covers.

Experiments

Experiment 1

Question

A question was asked in class today. That question was, what would happen if the “break” argument inside a function was replaced with the “exit” command? Would this cause just the function embedded within a program to end or would this cause the entire program to unexpectedly exit?

Resources

C Programming Language Second Edition C Pocket Reference

Hypothesis

Based on what I have learned about the C programming language thus far, I believe that the use of the exit command within a function will only cause the function to exit and not the entire program due to the fact that the exit argument would only be in scope with the current function and not the rest of the program.

Experiment

To test my hypothesis I am going to modify a program that was created in class on March 1, 2012. I will first however execute the program as it was created and record the resulting output so I will have something to test against and compare data with. The program that I will be modifying is the same program that brought about this interesting question. I will modify one of the functions within the program to reflect the arguments in question, then compile the program, execute it and record the resulting output. By comparing the output from the two I will then be able to draw a conclusion about the arguments in question.

Data

This is the original code that I will utilize in this experiment.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
 
int iseven(int value)
{
        int tmp;
        tmp=value % 2;
        return(tmp);
}
 
void add(int *list, int total, int value)
{
        int i, s=0;
        for(i=0; i < total; i++)
        {
                if(*(list+i)==-1)
                {
                        *(list+i)=value;
                        s=i;
                        break;
                }
        }
}
 
int *init(int total, int *status)
{
        int i, *tmp;
        *status=0;
        if(total > 0)
        {
                tmp=(int*)malloc(sizeof(int)*total);
                for(i=0; i < total; i++)
                {
                        *(tmp+i)=-1;
                }
                *status=1;
        }
        return(tmp);
}
 
int main(int argc, char **argv)
{
        int *list, i, x=0;
        list=init(atoi(*(argv+1)),&x);
        if(x==0)
        {
                fprintf(stderr, "Error on initialization!");
                exit(1);
        }
        for(i=0; i < atoi(*(argv+1)); i++)
        {
                add(list, atoi(*(argv+1)), (rand()%atoi(*(argv+2))));
        }
        for(i=0; i < atoi(*(argv+1)); i++)
        {
                if(iseven(*(list+i))==0)
                {
                        fprintf(stdout, "%d is even\n", *(list+i));
                }
                else
                        fprintf(stdout, "%d is odd\n", *(list+i));
        }
        return(0);
}

This is the output received from the unmodified code.

lab46:~/src/cprog$ ./iseven 5 30
13 is odd
16 is even
27 is odd
25 is odd
23 is odd
lab46:~/src/cprog$

The following is the code that has been modified to reflect the question above. Note the change in the “add” function, the “break” statement has been changed to an “exit” statement with a return code of zero. Also note the inclusion if the new printf statements within each function. These are included so I am able to tell how far the program progresses.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
 
int iseven(int value)
{
        printf("Diag 1\n");
        int tmp;
        tmp=value % 2;
        return(tmp);
}
 
void add(int *list, int total, int value)
{
        printf("Diag 2\n");
        int i, s=0;
        for(i=0; i < total; i++)
        {
                if(*(list+i)==-1)
                {
                        *(list+i)=value;
                        s=i;
                        exit(0);
                }
        }
}
 
int *init(int total, int *status)
{
        printf("Diag 3\n");
        int i, *tmp;
        *status=0;
        if(total > 0)
        {
                tmp=(int*)malloc(sizeof(int)*total);
                for(i=0; i < total; i++)
                {
                        *(tmp+i)=-1;
                }
                *status=1;
        }
        return(tmp);
}
 
int main(int argc, char **argv)
{
        printf("Diag 4A\n");
        int *list, i, x=0;
        printf("Diag 4B\n");
        list=init(atoi(*(argv+1)),&x);
        printf("Diag 4C\n");
        if(x==0)
        {
                fprintf(stderr, "Error on initialization!");
                exit(1);
        }
        printf("Diag 4D\n");
        for(i=0; i < atoi(*(argv+1)); i++)
        {
                printf("Diag 4Da\n");
                add(list, atoi(*(argv+1)), (rand()%atoi(*(argv+2))));
                printf("Diag 4Db\n");
        }
        for(i=0; i < atoi(*(argv+1)); i++)
        {
                if(iseven(*(list+i))==0)
                {
                        fprintf(stdout, "%d is even\n", *(list+i));
                }
                else
                        fprintf(stdout, "%d is odd\n", *(list+i));
        }
        return(0);
}

The following is the resulting output after the modifications were made to the original code, and the code was compiled and executed.

lab46:~/src/cprog$ ./iseven 5 30
Diag 4A
Diag 4B
Diag 3
Diag 4C
Diag 4D
Diag 4Da
Diag 2
lab46:~/src/cprog$

Analysis

Based on the data collected:

It turns out after reviewing the collected data that my original hypothesis appears to be incorrect. The modified program runs to the point of calling the “add” function. When the program calls the “add” function, the function is executed and the “exit” function is read which then terminates the entire program instead of terminating the parent function and returning back to the “main” function to allow the program to complete.

Conclusions

I have concluded that it does matter where the “exit” function is located within a program due to the fact that it will terminate whatever is happening at that point in time. Within the scope of this experiment and the above program it is best to use the “break” function to allow the program to continue its function and complete the program routine.

Experiment 2

Question

What is the question you'd like to pose for experimentation? State it here.

Resources

Collect information and resources (such as URLs of web resources), and comment on knowledge obtained that you think will provide useful background information to aid in performing the experiment.

Hypothesis

Based on what you've read with respect to your original posed question, what do you think will be the result of your experiment (ie an educated guess based on the facts known). This is done before actually performing the experiment.

State your rationale.

Experiment

How are you going to test your hypothesis? What is the structure of your experiment?

Data

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

Analysis

Based on the data collected:

  • Was your hypothesis correct?
  • Was your hypothesis not applicable?
  • Is there more going on than you originally thought? (shortcomings in hypothesis)
  • What shortcomings might there be in your experiment?
  • What shortcomings might there be in your data?

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.

Experiment 3

Question

What is the question you'd like to pose for experimentation? State it here.

Resources

Collect information and resources (such as URLs of web resources), and comment on knowledge obtained that you think will provide useful background information to aid in performing the experiment.

Hypothesis

Based on what you've read with respect to your original posed question, what do you think will be the result of your experiment (ie an educated guess based on the facts known). This is done before actually performing the experiment.

State your rationale.

Experiment

How are you going to test your hypothesis? What is the structure of your experiment?

Data

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

Analysis

Based on the data collected:

  • Was your hypothesis correct?
  • Was your hypothesis not applicable?
  • Is there more going on than you originally thought? (shortcomings in hypothesis)
  • What shortcomings might there be in your experiment?
  • What shortcomings might there be in your data?

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.

opus/spring2012/brobbin4/part1.txt · Last modified: 2012/03/04 22:16 by brobbin4