Lauren's Fall 2011 Opus
My name is Lauren. I moved to Elmira from Buffalo two years ago. This fall marks my first full year at CCC. I previously attending Buffalo State University, and I am majoring in Computer Science.
Today, I accessed my Lab 46 class email, as well as joined the CPROG mailing list. This was significant because most of the communication for this class will be done through this email, whether it be between students or important information from the teacher to the students. Joining the CPROG mailing list was significant to me because it was the first time I was able to full experience the lab 46 email functions. It was the first email I received on this account, and it was the first time i sent an email from that account as well. I took this opportunity to play around with the different options given, such as learning how to 'delete', 'save', and 'send'. At first, I did not realize the '^' symbol really meant to press 'ctrl' (and then the command key). I struggled with this for a while until finally, after some experimenting, was able to successfully send and delete emails. When I first tried setting up my lab 46 email, I felt overwhelmed and immediately assumed since I was not understanding everything all at once that I was behind in the class. After re-reading some information and experimenting, I realized that I was not behind and that I may have been just stressed and a bit confused by new things. I am looking forward to using the putty program more and getting more experienced.
Today I accessed the class IRC, which is more or less a chat room for the students in the class. This was significant because I was able to see what my fellow classmates were struggling with by reading what questions they had, and I also learned some things by reading the answers given by others, probably more experienced, than myself. This aid is going to be useful to me when I have questions for others regarding assignments or a topic given to us to read about. I almost see this chat room as a classroom setting: if we were to have this online class in person, this chat room would be what the every day setting would be like, with the questions and answers given, as well as everybody's personalities shining through and getting to know some people. I was having trouble at first trying to figure out how to close the screen and exit the chat room, but after doing some research and reading, I was able to figure out what I was doing wrong.
Today I read about how to write basic lines of code using C. I learned that it is important to define variables at the beginning of the code, so when a variable is used, it has a meaning that the compiler can refer back to in order to make sense of the code. I also learned how to create a comment in a line of code, which is basically for use of the programmer. A comment is more like a note that the programmer can refer back to at a later date as a reminder for something. This is an important tool to learn how to use because the compiler does not read comments in a line of code and try to print them, it is basically disregarded. I learned that escape sequences in a line of code tell the complier to do a specific task, such as create a new line of code at the end of a command. All of these commands are important to learn because they are basics when it comes to writing code, and will be used frequently.
Today I wrote my first code in putty, just the basic “hello, world” code from our textbook. I was very excited and proud of myself when I successfully completed this task. I needed assistance in getting to the screen which allows us to write code in putty. Once I got step by step instructions on how to do this, and once I successfully executed this task, I felt motivated and excited to do more. When I logged into putty, at the command prompt I typed “cd ~/src/cprog”. From there, I created a new source file to add to my repository by typing “svn add hello.c”. Once this was created, I went into the nano editor by typing “nano hello.c”. From there, I was able to write the 'hello, world' code given in the textbook. Once finished, I saved the code. Then when I went to compile the program, a the command prompt I typed “gcc -o hello hello.c”, then to run the compiled program i typed “./hello”. When all of this was done, I was given the output of “hello, world” successfully, without any errors.
A variable is a word given with a specific value, listed before the code, that the compiler can reference when running lines of code. char: character, 1 byte short int: short integer, 2 bytes int: integer, 4 bytes long int: long integer, 4 bytes bool: boolean value, 1 byte float: floating point number, 4 bytes double: double precision floating number, 8 bytes long double: long double precision floating number, 8 bytes
int a; int b; int c;
A pointer is a data type used in C that holds the address when a value is stored in the memory. So basically, instead of a pointer containing any actual data or a value, it “points” to the memory location in which the value, or data, can be found.
#include <stdio.h> void main() { int nNumber; int *pPointer; nNumber = 15; pPointer = &nNumber; }
A character string is a command sentence, given in double quotes, that lets the program know what characters, or words, the user wants to print when the program is run.
The format parameter is followed by a string of characters that contains the text to be written. The number of arguments following the format parameter should contain at least as many as the number of format tags
int printf ( const char * format, ... );
Arithmetic Operators are used to perform some mathematical operations like addition, subtraction, multiplication, division, etc. Normally, these operations are performed on an expression. + : additive operator - : subtraction operator * : multiplication operator / : division operator % : remainder operator
#include <stdio.h> main() { int fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; } }
Logic operators compare boolean expressions and give a boolean result. The AND (&&) operator performs logical conjuction between 2 boolean expressions. If both expressions are evaluated to be true, then the AND operator will give the result 'true'. The OR ( || )operator performs logical disjunction between 2 boolean expressions. If one or the other expressions evaluate to true, then the OR operator will result in 'true', if neither of the expressions evaluate to true, then the result given is 'false'. The XOR operator performs logical exclusion on two expressions. If only one expression evaluates to true, then the XOR operator will result in 'true'. If both of the expressions evaluate to either true or false, then the XOR operator will result in 'false', just as long as both expressions evaluate the same. The NOT (!) operator performs logical negation on a boolean expression.
#include <iostream> using namespace std; int main() { !(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true. !(6 <= 4) // evaluates to true because (6 <= 4) would be false. !true // evaluates to false !false // evaluates to true. }
Typecasting is making a variable of one type, (for example, an int), perform like another variable, (for example, a char), for one single operation.
#include <iostream> using namespace std; int main() { cout<< (char)65 <<"\n"; // The (char) is a typecast, telling the computer to interpret the 65 as a // character, not as a number with a value. It is going to give the character output of // the equivalent of the number 65. cin.get(); }
The scope of an identifier is the biggest part of the program text where the identifier can possibly be used to reference it's object. A local scope can be used in a block and in blocks enclosed within that block, but the name must be declared before the lines of code before it is used, otherwise the program will not run correctly. A name has file scope if the identifier's declaration appears outside of any block. Global scope is the namespace scope of a program that occurs on the outside, in which objects, functions, etc. can be defined. A name has global scope if the identifier's declaration appears outside of all blocks.
int x = 4; /* variable x defined with file scope */ long myfunc(int x, long y); /* variable x has function */
An array is a data structure, which is a specific way of storing information in a computer, which entails a selection of variables, each of which is identified by one integer. Pointer arithmetic can be used to access an array or act like an array.
#include <stdio.h> int main() { short age[4]; age[0]=23; age[1]=34; age[2]=65; age[3]=74; return 0; }
Multi dimensional arrays are simply several arrays put into one array, most commonly multi dimensional arrays are 2 arrays put into one. Multi dimensional arrays are not limited to two arrays into one, but the more arrays used means more memory is used as well. When creating a multi dimensional array, we must use two nested brackets. This gives us a counter variable for every column and every row in the arrays.
#include <stdio.h> int main() { int[][] myArray = { {0,1,2,3}, {4,5,6,7} }; ); }
Unions are a structure that is used to define a data type with more than one field, and each field takes a separate storate location. A union defines a single location that can be given many different field names. Typedef is a statement that allows the user in C++ to define their own variable types, instead of being restricted to the basic variables that have been taught. Enum stands for enumerated data type that is designed for variables that contain only a limited set of values. These values are referenced by the compiler as name, and assigns each name an integer value
union value { long int i_value; // Long integer version of value float f_value; // Floating version of value } typedef int day_of_the_week; // Define the type for days of the week const int SUNDAY = 0; const int MONDAY = 1; const int TUESDAY = 2; const int WEDNESDAY = 3; const int THURSDAY = 4; const int FRIDAY = 5; const int SATURDAY = 6;
A command line argument can be defined as any parameter that is typed after the name of a program
In the example: dir *.txt
'dir' would be the name of the program to run, and '.txt' would be the command line argument
A header file is a file containing C declarations to be shared between several source files. In order to reference a header file in your code, you must “include” it by writing '#include' at the front of each source file. System header files declare the interfaces to parts of the operating system. The user includes them in the program to supply definitions and declarations needed to make system calls and libraries. In C, it is common to see header files names that end with .h .
#include <filename> #include <stdio.h>
The main difference between structures and classes is that structures have public access and classes have private access. This essentially means that the user who wrote the code chooses to have certain variables private, usually a value is given, and when it is referenced within a line of code, the variable itself will not appear, but the value will appear. If the user defines a structure and then delcares an object of that structure using the word “class”, the object is still public.
Write an example of a structure and a class
#include <stdio.h> struct point { int x; int y; } int main() { x = 1; y = 2; return 0; }
class Box { double Length, Width, Height; char Color[12]; float Boxsize; };
I attempted to write very simple, short lines of code for examples of each: a structure and a class. I simply tried to show examples of how each variable should be declared in a program. When it comes to the example I listed for a class, ideally the program would give results for the length, width, height, color, and size of a box when each were defined within the lines of code. In my structure example, I tried to introduce a structure declaration (which is a list of declarations enclosed in braces). I believe the measurement process could definitely be enhanced to prove a more effective example, and maybe after having more experience with these variables, I eventually will be able to do so without the risk of error. I attempted to simply describe and show very brief declarations of the use of a structure and a class.
What would happen if I were to write a simple code in C, and leave out the header file? What is the importance of the header file?
http://gcc.gnu.org/onlinedocs/cpp/Header-Files.html This website has a brief description of what a header file is, as well as how to include it into a code. In C, it is typical to have a header file that ends with “.h”. The declarations listed in the header file can be used in more than one source file, and it is easier to just include the header file at the beginning of the code instead of copying the header file into each source code that needs it.
http://www.suite101.com/content/c-header-files-a2936 This website describes how to create a separate source code file to contain a function that provides additional processing capabilities. In these situations, it is required to provide a user defined header file so that the compiler knows how to call this function.
I believe if I remove the header file in a simple code (in this case, I will use the “hello, world” code given in the textbook), I will get an error message when I try to run the program.
I am going to go to putty, create the source file hello.c, write the code (which is given to me in the textbook), and leave out the header file. I will save this code, compile, and run the program to see what happens.
This is the code I entered into putty:
main () { printf("hello, world\n"); }
After I saved, compiled, and tried to run this program without the header file, this is the result I got:
lab46:~/src/cprog$ gcc -o hello hello.c hello.c: In function 'main': hello.c:5: warning: incompatible implicit declaration of built-in function 'printf' lab46:~/src/cprog$
My hypothesis was correct in guessing that I would receive an error message when I tried to run a program without the header file. This means that the program did not know what I wanted from it when I asked it to print the words “hello, world” without the declaration, or definition, given for “printf”, which would have been accessed from the header file, which I left out of the code. Without previously definied variables, which are stored in the header file, the code cannot execute any commands given by the user, since it does not understand what I am asking of it. It is like trying to learn Spanish without a Spanish to English dictionary: the computer had nothing to reference when the command was given.
I have learned that header files are essential when creating a code. If the user expects the code to run properly, it is necessary to add a header file to the code so the compiler understands the commands given by myself and what I want from it. If the compiler does not know what “printf” means, then it will not print the words for me (in this case, 'hello, world'). If printf is not previously declared or defined, the program is doomed to fail.
What will happen if I write a code in C and I do not put the “\n” after the printf argument? What is it's purpose, why is it so important?
http://www.cplusplus.com/reference/clibrary/cstdio/printf/ This website shows an example of a short code written, and then the same code compiled and what it should look like when properly done. The code has several uses of “\n” and the result. http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V40F_HTML/AQTLTBTE/DOCU_003.HTM This website explains the necessity behind the newline character, and gives a brief definition.
I believe I will get an error when I try to run a code without the newline character present, because when the code is run, the compiler will not be able to determine where the command ends and what the user wants.
I am going to write the “hello, world” code into putty, and I will leave out the newline command, then run the program.
When I removed the newline command from the program and then tried to run the program, I did not receive an error message, but this is what resulted:
lab46:~/src/cprog$ ./hello hello, worldlab46:~/src/cprog$
My hypothesis was not exactly correct, I had guessed that I would receive an error message when I tried to run the program without the newline character. Instead, the program ran the output of “hello, world” but did not leave any space between the output and the command prompt, as shown above. In a way, I was correct when I said the compiler would be confused by my code, but it still ran the program, it was just a jumbled mess instead of an error message. Looking back, it makes sense why the program would have tried to run instead of producing an error message, which is what I originally thought. Now that I have seen what happens when you do not add the newline character, I understand how the compiler would still run the code, it just (simply put) was not neat and tidy had I added the newline character. This being the first code I wrote in C, I was unsure of what the results would yield, even when one of the most basic commands was used improperly.
I can conclude from my findings that even though the newline character is important for clarity and neatness, it is not 100% essential when running a program. It definitely makes the code easier to read, but leaving the character out of the code does not prevent the compiler from running it successfully, it would just take exra time to read it, given that the lines of code would be all unorganized.
In the “Hello, world” program, what would happen if I added the character “\c” in the printf argument?
Up to this point in the textbook, we do not know what the character “\c” stands for, or what it does. That being said, I did some research on the internet about the printf arguement. http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.cmds/doc/aixcmds4/printf.htm This website explains and gives examples of the printf command. Essentially, the printf command simply writes an output given by the user in a line of code. http://linux.about.com/library/cmd/blcmdl1_printf.htm This website clearly lists and explains several characters and commands commonly used with the printf argument
I believe I will receive an error message when I try to run the program with a “\c” randomly placed within the lines of code. I think this because I have tried researching on Google what the “\c” character means and what it does, but I was unable to find anything about it.
I am going to test this hypothesis by editing my “hello, world” program in putty, insert a “\c” after the esacpe command, and running the program.
lab46:~/src/cprog$ gcc -o hello hello.c hello.c:5:9: warning: unknown escape sequence '\c' lab46:~/src/cprog$ ./hello hello, world c lab46:~/src/cprog$
I was wrong in assuming I would receive an error message, instead I noticed that the program ran smoothly and the output was the same “hello, world”. The difference I noticed was that the line after the output from the code, I saw that the command prompt was preceeded with a “c”.
I can conclude that the “\c” is not a variable in need of a definition within the lines of code, but it is a command for the following line of code. I am unsure what the character actually means when it comes to running a program with this character within it.
Today I read a little bit more about binary arithmetic operators. The signs are + (addition), - (subraction), * (multiplication), / (division), and the modulus operator %. The modulus operator prodices the remainder number (if applicable to the math problem) when two numbers are divided together. This operator can only be used on integers and not on floats or doubles. At first, this was difficult for me to understand when I was reading the book on this operaton. I did some online research and then I was able to find some more information on this topic, and I was able to better understand that “modulus” is practically another word for “remainder”. When reading about arithmetic operators, I tried thinking about writing a program almost as if I were on the inside of a calculator: when we put numbers into a calculator and get the result, it happens so easily. It was interesting to think about what goes on “behind the scenes” (so to speak) of everyday machines.
#include <stdio.h> void main() { int total = 45; int divider = 7; int a = 0; int b = 0; a = total/divider; printf(" total is %d and divider is %d", total, divider); printf("\n a is %d.", a); /* left over */ b = total%divider; printf("\nThere are %d left over.\n", b); }
Today I worked on an assignment for another computer class of mine (CSCS 1200) based on programming. This teacher had us download Microsoft Small Basic, which is a very user friendly, first-timer program used to write code. I found this to be extremely helpful (and, obviously, a lot easier to use) because when I began typing a command, such as “TextWindow” and “WriteLine”, Small Basic tried guessing what I was asking of it, and in the toolbar section popped up a helpful aide listing suggestions of what I might be trying to do, along with a description of what the command means. Also, instead of having to save the file in a repository and then write a specific line of code in putty to run the program, there is a simple button that says “run” to click on, and Small Basic runs the program for you instantly, in a seperate window, so it makes things look a lot less jumbled and confusing. I found that Small Basic was just easier on the eyes with a white background in the window and normal black text, or in some cases, different colored text, in which the colors symbolized a certain command. Overall, I found Small Basic a lot easier to work with rather than work with putty, but that was to be expected, seeing as Small Basic is for beginners. I just overall found the similarities and the differences interesting.
Today I did an experiment (listed as Experiment 1 below) about arithmetic expressions. I was curious to see if my program would output negative numbers when I subtracted 20 from 10. I did some research and discovered that as long as I used the modulus operator properly in my program, I would receive the desired output, which was a -10. As I was writing my program and attempting to run some tests on it, I discovered how to write a program where the user can input the numbers to get a result, rather than dedicate values to variables. I found this method to be useful, and more fun, because I was able to try different numbers as the input (such as ridiculously high or low numbers) just to play around with the program and make it more interesting. I found this to be a lot more interactive and creative instead of just assigning values to variables and running the program. I also think learning this will be more useful down the road.
Today I did an experiment about height. I wrote a program based on user input, which had various outputs depending on what number was entered into the program. If the number was less than 5 (as well as in decimal form, not using ' or “) the output should read “you are short”. If the input was between 5 and 6, the output should read “you are average”, and if the input was greater than 6, the output should read “you are tall”. I enjoyed writing this program because I like writing things that have user interaction, rather than write a code that has assigned values to variables and just compiling and running the program without any interaction by the user. I find this to be more challenging and creative, and I enjoy thinking up situations where user input could be used and different outputs could be given. In this particular program, I focused on using “if” and “else” statements, and I did some research online as well as reading what the book has to say about them in order to properly use them within my program.
Standard input is basically whatever the user types into the code from the keyboard. Meaning, whatever text is entered, the program reads and interpretes it. Standard output is typically the screen in the session, which means whatever the program prints from the standard input, it appears in the standard window.
#include <stdio.h> #include <ctype.h> int main() { int c; while ((c = getchar()) ! = EOF) putchar(tolower(c)); return(0); }
A parameter is generally used for a variable named in the list in a function definition. An ordered list of parameters is usually included in the definition of a function.
#include <stdio.h> double sales_tax(double price) { return 0.05 * price; }
A return statement causes the execution to leave the function and start again at the point in the code right after where the function was called. A return type is usually set at zero in C programming and set at the end of the written program. The zero return value from main generally means that a normal program exit is represented. Non zero values indicate unusual or wrong termination conditions.
#include <stdio.h> power(base, n) int base, n; { int i, p' p = 1; for (i = 1; i <= n; ++i) p = p * base; return p; }
Recursion is a programming technique that allows the user to express operations in terms of themselves. It is similar to a loop because it repeats the same code, but it requires passing in the looping variable. This function can simplify some tasks.
void recurse() { recurse(); //Function calls itself } int main() { recurse(); //Sets off the recursion }
The C library consists of a set of sections of the ANSI C standard which describes a collection of library routines used to fulfill common operations, such as input/output and string handling. This is essential in C because anything and everything that follows the listed C library in the program references the library in order to understand what the user wants the program to output. stdio.h is the C library to perform I/O operations.
#include <stdio.h> /* this is the C library listed for this program */ int main() { printf("The C Library is essential to any code\n"); return(0); }
A compiler, or a linker, is the program that generates the executable file by linking (which essentially means several object files are merged to create one executable file). A compiler is important because it translates human readable source code into machine code. It is the “middleman” between humans and machines. In the following code example, the compiler searches for a definition of the function “printf” and finds it in the header file, which is ”#include<stdio.h>“, and then creates a file successfully.
#include<stdio.h> int main() { printf("Lauren"); return 0; }
A preprocessor is a program that processes its input data to produce an output that will eventually be used as the input data to another program. When it comes to the C preprocessor, the '#' sign is usually followed by the preprocessor. The following example shows the most common use of a preprocessor, which is to include another file in a program. The preprocessor replaces the line ”#include <stdio.h>“ with the header file of that name, which declares the printf() function (as well as declaring other things).
#include <stdio.h> int main (void) { printf("Hello, world!\n"); return 0; }
A makefile is a way of associating short names with a series of commands to execute when called upon to do so by the user. The makefile has instructions for a specific project. The default name of the makefile is literally 'makefile', but the name can be specified with a command-line option.
project.exe : main.obj io.obj tlink c0s main.obj io.obj, project.exe,, cs /Lf:\bc\lib main.obj : main.c bcc –ms –c main.c
Source code is a language written by the user in a program, which is then translated to binary code that the computer can directly read and execute to perform whatever task the user requests of the program.
#include <stdio.h> int main() { int counter = 0; int numTimes = 0; cout << "How many times do you want to see Lauren?: "; cin >> numTimes; cout << "\n"; while (counter < numTimes) { cout << "Lauren!\n"; counter++; } cout << "\n"; return(0); }
Object code is the binary representation of the assembly output of the compiler. It is the way the computer represents programs internally after receiving input from the user in source code.
color c = color(0); float x = 0; float y = 100; float speed = 1; void setup() { size(200,200); } void draw() { background(255); move(); display(); } void move() { x = x + speed; if (x > width) { x = 0; } }
A library is a collection of resources used to develop software. These may include pre-written code and subroutines, classes, values or type specifications. A library is essential to be listed at the beginning of a code in order for the computer to understand what the user is asking to be compiled. It is also possible for the user to create their own library using their own names or shortcuts, as long as each name has a definition. The following default example states “stdio.h” as the library used in the specific code.
#include <stdio.h> int main() { printf "hello world\n"; return(0); }
In order to compile a program that has been divided into multiple source files, you would simply list all of the files the user wished to compile after typing the command “gcc -o”. If the user wished to name a file to create after compiling all of the files listed, they would simply type the name of the file the user wished to create after “gcc -o” and before all of the file names being compiled.
gcc -o executable sourcefile_1.c sourcefile_2.c sourcefile_3.c gcc -o mydb main.c keyboard_io.c db_access.c sorting.c
Understand the difference between procedural and object-oriented languages. The idea behind procedural programming is to disect a programming task into variables and data structures. Object-oriented programming disects a programming task into classes.
Doing some online research, as well as textbook research, to determine the similarities and differences between procedural programming and object-oriented programming.
A significant differnece between procedural programming and object-oriented programming is that procedural programming uses procedures to operate on data structures, object-oriented programming combines the two together so an object, which is an example of a class, operates on its own data structure. Object-oriented programming focuses on representing real world object problems and their behavior. Procedural programming deals with representing solutions to problems using procedures, which are collections of code that run in a specific order. One thing to remember is that object-oriented programming and procedural are two ways of representing problems to be solved, and it does not matter which language is used. Basically, object-oriented programming languages can be used for procedural programming while procedural languages can sometimes be used for object-oriented programming.
I think with a little research on the internet, as well as in the textbook, I was able to differentiate between object oriented programming and procedural programming successfully. It was a bit difficult to wrap my mind around the two topics at first, especially when the topics don't deal with something that is experienced by the user when physically writing a program. For instance, it is easier to understand what an array or string is when writing a program because I can see the topic being put to use. The measurement process could be more effective if the user were to cite examples. To say “demonstrate” the difference between object-oriented programming and procedural programming is a little vague: it is easier to understand what is being asked if it were to say “give examples” or “explain the difference” instead of the word “demonstrate”. I felt that word left the objective open to interpretation, which I took to mean “explain”. On the other hand, leaving the objective open ended could be useful to see different types of responses from different people.
What would happen if I were to add 2 numbers together that would receive a negative number output?
http://www.trunix.org/programlama/c/kandr2/ This website explains basic arithmetic operations, and mentions using the modulus operator when expecting a negative answer as a result
http://publications.gbdirect.co.uk/c_book/chapter2/expressions_and_arithmetic.html This website explains the use of double and float variables when it comes to arithmetic expressions
Based on my research, if I use the proper modulus operator in my program, I will be able to get a negative result if I subtract 20 from 10.
I am going to write a program in putty declaring x and y as integers with the values of 10 and 20, and then write a small program subtracting the two from each other to hopefully yield a result of -10.
Code written:
#include <stdio.h> int main() { int firstNum, secondNum, delta = 0; printf("Enter first number (a): "); scanf("%d", &firstNum); printf("Enter second number (b): "); scanf("%d", &secondNum); delta = firstNum - secondNum; printf("a - b = %d\n", delta); return 0; }
The following code shows the entry of numbers I put in when prompted, and the output:
lab46:~/src/cprog$ ./numbers Enter first number (a): 10 Enter second number (b): 20 a - b = -10
My hypothesis was correct in guessing that I would receive a negative output when I properly inserted an arithmetic expression in my program. I found it a lot easier to assign my integers with the value of 0, and then input numbers myself when prompted to do so by the program instead of assigning values to each integer and then writing an arithmetic expression from there. Also, it was more fun to play around with the program and enter different numbers rather than just writing a program where the integer values were restricted to what was assigned by the user.
I discovered that when the modulus operator is used properly within a program, the output will yield the result expected. This also goes for any other arithmetic expression: whether it be addition, subtraction, multiplication, or division, when used properly within a program, and having the proper integers assigned in the first place, the expected results will be obtained. Also, when I went into this experiment, I did not anticipate writing a program where the user inputs the values of the integers at the prompt. Instead, I had originally planned on assigning values to the integers and then writing an expression to yield a result. As I was writing the code, I decided to challenge myself a little more and go a step further.
If I write a program that allows the user to input their height, will I get the correct response when I enter in various heights?
http://cboard.cprogramming.com/c-programming/92579-usefulness-else-if-statement.html I looked at this message board for some tips on the “else if” statements, how to use them, and how they can be useful in programs. I referenced this person's program on age and changed mine to height and added more options to the outputs. http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_025.htm This website is useful when it comes to different uses for “else if” statements, and explains how to use them properly by citing several different examples.
I believe (as long as I write the code correctly) that I will receive the dedicated output when I enter in various heights into my program when prompted to do so. By doing some reserach on “else if” statements, as well as reading what is in our textbook, I believe I will be able to compile together a simple code that allows the user to enter their height (as long as the input is “5.3” and not “5'3””) and a specific statement about their height will be the output.
I am going to write a simple program in putty that allows the user to enter their height in decimal form to receive a specific output based on their height.
This is the program I wrote:
#include <stdio.h> int main () { int height; printf("Please enter your height"); scanf("%d", &height ); if ( height < 6 ) { printf ("You are average height\n"); else if ( height > 5 ) printf ("You are average height\n"); else if ( height < 5 ) printf ("You are short\n"); else if ( height > 6 ) printf ("You are tall\n"); } return 0; }
This is my input and result:
lab46:~/src/cprog$ ./height Please enter your height5.3 You are average height lab46:~/src/cprog$
My hypothesis was correct in assuming that when I entered my height of 5'3“ (in decimal form, 5.3) I would receive the output “You are average height”. If I were to input anything lower than 5, the output should be “You are short” and if I were to input anything greater than 6, the output should be “you are tall”.
I conclude that as long as the “if” statements are used properly within a program, the output based on the input should be correct. I also have a great deal of fun compiling programs based on user input, rather than just assigning concrete values to variables and running a program without any interaction.
This week, I did my first project for this course entitled “Exploring Arithmetic Operators”. In this project, I dealt with defining all of the arithmetic operators used in C programming, as well as using all of them in a program I wrote from scratch. In this program, my objective was to write a code that allowed the user to type in any numbers they wanted to add, subtract, multiply, and divide. The program prompted the user to input numbers seperately, and then (based on where the user was in the program), the numbers were either added, subtracted, multiplied, or divided. The program warned the user beforehand what operator was being used. It turned out this project was a success after running a test set of numbers. This was significant because it was my first project submitted in this course, and I found it to be intimidating at first, but then realized it was much easier than I originially thought it would be. This was a good jumping off point, project-wise, for me, because it was relatively simple, yet it dealt with several different aspects of C programming that are essential to being successful in this course.
Today in another computer class I am currently taking this semester (CSCS 1200), we were assigned reading about the world wide web. I found this assignment to be interesting and informative, since this is something that I personally use countless times a day. The world wide web is something that, I believe, people now take for granted and do not fully appreciate the background of the world wide web. For example, CGI (Common Gateway Interface) is a set of standards for how servers can handle a variety of HTTP requests. ASP (Active Server Pages) is an alternative to CGI that runs on server and deals with data submitted by the user. This is the kind of things I found interesting in my reading for the week, since this is something people use every single day, yet most probably have no idea how they access the internet. All people really know is how to click on an icon and type things into Google. These types of topics are things I enjoy learning about in my computer classes (kind of like looking behind the scenes).
Today I completed a project about pointers and arrays. I decided to choose this as a topic for my project so that I could focus more on pointers and how they are used within a program. This topic has given me some problems in the past, and has brought on some confusion, so I took this opportunity to spend some more time on pointers and get some more practice with them. In my reserach for pointers, I came across a website that explained how to use function pointers, which I found to be useful and informative. I learned that function pointers could assist the programmer in using pointers as different behaviors at different times. I also learned how to delcare a pointer using the '*' operator, and I learned about pointer arithmetic (++, –, -=, += ). These topics, along with others I researched to complete my project, were useful and informative, and overall I feel like I have a better grasp on pointers.
This week for my CSCS 1200 class, we were instructed to review the past two months worth of work we have been doing to prepare for a test this coming week. While doing this, I came across a section in my book about object oriented programming, which we also learn about in this class. Examples of object oriented programming include visual basic, java, and C++. In my textbook, there is a helpful diagram to assit the reader in understanding object oriented programming, which basically consists of showing existing objects combining with new objects to form an object oriented program. We also focused on operating systems, which is a set of computer programs that runs the computer hardware and acts as an interface with both application programs and users. Some examples of an operating system is microsoft windows and apple OS X. I found it interesting how these two classes this semester has overlapped in some way, in CSCS 1200 I am able to “go behind the scenes” of the computer, and learn what makes it tick. In this class, we go into deeper topics and look at the details by learning how to write a program. I found it useful to take both classes at the same time, since at one point or another, each class as helped me with the other.
Namespaces let the user group variables like classes and functions under a specific name. Under a namespace is all of the declarations needed to complete the program. One identifier listed in a namespace may be used in another namespace, but will not necessarily have the same meaning under the two namespaces. In C++, a namespace is used in a namespace block, and within this block, identifiers can only be used as they are declared. If an identifer is used outside of the namespace block, then the identifier needs to show that it is being used in the namespace by typing “using namespace x;” in front of the identifier.
#include <iostream> using namespace std; namespace x { int a = 4; }
Input streams are used to save input from the user, output streams are used to save output for a particular object, such as a file or a printer. This means that the stream saves the information by the user to put into action at a later time when, for example, a printer is done warming up and is ready to print. Some devices are capable of being both input and output sources. Cin: standard input stream; when the user goes to type up a code in C++, “cin” is the object used to input data. Cout: standard output stream; when the user is typing up a program, “cout” is the object used to store the output data Cerr: standard output stream for errors
#include <iostream> int main() { int x; cout << "enter a number: "; cin >> x; return(0); }
Casting means the user changes the definition of a variable by changing its type to a different one. In order to type-cast an object to another you use the traditional type casting operator. This is used in C++ so that the user can make a variable of one type act like another type just for one single operation.
int i; double d; i = (int) d;
The standard template library provides C++ users with a specific set of tools that can be used for most types of applications. STL is the C++ standard library that contains four components called algorithms, containers, functors, and iterators. STL is specified by a set of headers, while ISO C++ does not specify headers.
#include <iostream.h> #include <list.h> // The STL list class int main () { int x; return 0; }
The “this” pointer is a pointer that can be used only with the nonstatic member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a “this” pointer. “This” pointer stores the address of the class instance, is not counted for calculating the size of the object, and cannot be modified.
#include <iostream> using namespace std; class MyClass { int data; public: MyClass() {data=100;}; void Print1(); void Print2(); void MyClass::Print2() { cout << "My address = " << this << endl; cout << this->data << endl;}
Function templates are special functions that can operate with generic types, which means this allows the user to create a function template whose use can be changed to more than one type or class without repeating the entire code for each type. In C++ this can be done by using 'template parameters' which is a special kind of parameter that can be used to pass a type as argument.
template <class identifier> function_declaration; template <typename identifier> function_declaration;
Const defines a type that is constant (as the name suggests), and volatile defines a type that is volatile. Volatile allows access to memory mapped devices, allows the use of variables between 'setjmp' and 'longjmp', and allows the use of 'sig_atomic_t' variables. To use a const, the user declares a constant as if it was a variable but adds ‘const’ before it. The user has to declare it immediately in the constructor because the programmer cannot set the value later (as that would be changing it).
const int Constant1=96; volatile REGISTER * io_ = 0x1234;
The user can overload a function by declaring more than one function with the name in the same scope. The declarations of the function must be different from each other by types or the number of arguments in the argument list. When you call an overloaded function, the correct function is chosen by comparing the argument list of the function call with the parameter list of each of the overloaded functions with the same name. The following example is the correct way to not overload a function:
void print(int i) { cout << " Here is int " << i << endl; } void print(double f) { cout << " Here is float " << f << endl; } void print(char* c) { cout << " Here is char* " << c << endl; }
Operator overloading is where different operators have different meanings depending on their arguments. Operator overloading is generally defined by the language or the programmer. To overload an operator means to provide it with a new meaning for user-defined types. Overloadable operators include addition, subtraction, multiplication, and division.
a + b * c add (a, multiply (b,c))
An abstract class is a class that is meant to be specifically used as a base class. An abstract class contains at least one 'pure virtual function'. The user can declare a pure virtual function by using a pure specifier (= 0) in the declaration of a member function in the class declaration.
class AB { public: virtual void f() = 0; };
Polymorphism in C++ means that some code, operations or objects behave differently in different situations. In C++, a type of polymorphism is overloading. The term 'polymorphism' when used in C++, it refers to using virtual methods. In C++ virtual function is a member function of a class, is declared with virtual keyword, and usually has a different functionality in the derived class.
public interface IQuestion { string Text { get; set; } ArrayList Choices { get; set; } void DisplayAccumulatedResult(); }
namespace std { public class Animal { public virtual void Eat() { Console.WriteLine("I eat like a generic Animal."); } }
Inheritance is a way of reusing existing classes without changing them, therefore making relationships between them. Inheritance is almost like embedding an object into a class. Inheritance lets the user include the names and definitions of another class's members as part of a new class. Single inheritance is where a class can only derive from one base class, and multiple inheritance is where the user can derive a class from any number of base classes.
#include <iostream> using namespace std; class A { int data; public: void f(int arg) { data = arg; } int g() { return data; } }; class B : public A { }; int main() { B obj; obj.f(20); cout << obj.g() << endl; }
Know how to use arrays and pointers. I focused a lot on arrays and pointers in this past month. An array is useful for one name for a group of variables of the same type, that can be accessed numerically. A pointer “points” to a location in memory. They can make a program more efficient, and can help handle large amounts of data.
Write an example of an array and a pointer in a program(s) to display how both are properly used.
This is an example of an array:
#include <stdio.h> #define ARR_SIZE 5 int main(void) { static float const prices[ARR_SIZE] = { 1.99, 1.49, 13.99, 50.00, 109.99 }; auto float total; int i; for (i = 0; i < ARR_SIZE; i++) { printf("price = $%.2f\n", prices[i]); } printf("\n"); for (i = 0; i < ARR_SIZE; i++) { total = prices[i] * 1.08; printf("total = $%.2f\n", total); } return(0); }
This is an example of a pointer:
#include <stdio.h> void DoubleIt(int *num) { *num*=2; } int main() { int number=2; DoubleIt(&number); printf("%d\n",number); return 0; }
Both of these examples are taken from my project on arrays and pointers, found here:
http://lab46.corning-cc.edu/user/lburzyns/portfolio/project2
Since I happened to focus on arrays and pointers for the project I completed this week, I decided it would be fitting to choose arrays and pointers as this month's Opus objective. I feel like I have done copious amounts of research regarding these two topics in the past week, and I feel like I have demonstrated them properly in a program. I chose to do two seperate programs to display how to use arrays and pointers properly because it was clearer to me and better for me to understand these two topics if I seperated them and focused on each one individually. I found arrays very simple and easy to use, and actually enjoyed learning about them. Pointers were a little bit more tricky to understand, and have been giving me some trouble for some time now. After focusing on these two topics this week as much as I have, I feel like I have a much better grasp on pointers and I think I can better understand the logic behind them.
What would happen if I were to write a basic for loop program and at the end of the code, have the return be 0?
http://einstein.drexel.edu/courses/Comp_Phys/General/C_basics/#loops This website was helpful when it came to a basic introduction to loops. It is easy to understand because it takes the user through a line of code step by step. This was great for me because sometimes seeing a whole program and then seeing the explanation either before or after it is difficult for me to follow. This way, I can see what purpose each line of code served when it comes to the program as a whole.
http://computer.howstuffworks.com/c8.htm This website was useful in this experiement because it takes the user through all of the different types of loops C programming has to offer: else, else if, do-while, for loop, etc.
http://www.exforsys.com/tutorials/c-language/decision-making-looping-in-c.html I found this website particularly interesting and helpful because after a program was listed with an explanation, there is also a diagram drawn that helps the user physically see what the loops are doing within a program, rather than try to use your imagination while reading an explanation.
I expect there to be an error when I try to compile the program listing a return value at 0 at the end of the code. What should be there instead is “getchar();”, not “return 0;”.
I am going to write a very small, basic program that allows me to simply modify the code to my experiement, compile & run, and then report the results (along with the code written) here.
Here is the code written:
#include <stdio.h> int main() { int x; for ( x = 0; x < 10; x++ ) { printf( "%d\n", x ); } return 0; }
Here is the result when compiled:
lab46:~/src/cprog$ ./loops 0 1 2 3 4 5 6 7 8 9 lab46:~/src/cprog$
My hypthesis was incorrect. All adding “return 0” did was exit the program right after it was finished running, rather than wait for the user to exit the program manually. I should have realized that before making my hypothesis, it seems so obvious now that I have written the program and executed it. Had I written a program that allowed for user input, then maybe the return 0 function would have caused an error when I tried to run the program, but that was not the case with this experiment. It turned out that having either “return 0” or “getchar()” at the end of the program did not make a very big difference at all.
I have discovered how to successfully write a simple loop statement in this program, and I did not make any mistakes. The program executed just as I would have liked. After compiling my program, I realized that having a return 0 statement at the end did not make a very big difference to the program, rather it just exited the program for the user instead of waiting for user input.
How would I use functions to add, subtract, multiply, or divide numbers in a program?
http://www.cprogramming.com/function.html This website lists a lot of commonly used functions in C and in C++, the user is able to click on each function individually, and an explanation of the function is given, along with an example.
http://www.mycplus.com/tutorials/c-programming-tutorials/functions/ This website takes the user through a step by step introduction to functions by showing the structure, such as the header and the body.
http://computer.howstuffworks.com/c13.htm This website is great for beginners because it makes it very easy for the user to understand how to use functions and why they are used, along with several short examples given.
After researching how to use arithmetic as a function and not use the arithmetic operators, I believe I can successfully write a program that will add two numbers together (based on user input) by using the “sum” function.
I am going to write a small program in putty using the 'sum' function to add together two numbers the user chooses to input, and the output will yield the correct arithmetic.
Here is the code written:
#include <stdio.h> int sum ( int x, int y ); int main() { int x; int y; printf( "Please input two numbers to be added: " ); scanf( "%d", &x ); scanf( "%d", &y ); printf( "The sum of your two numbers is %d\n", sum( x, y ) ); getchar(); } int sum (int x, int y) { return x + y; }
And here is the output of the compiled code:
lab46:~/src/cprog$ ./functions Please input two numbers to be added: 5 6 The sum of your two numbers is 11
My hypothesis was correct, I was able to successfully compile a code using a function for adding together two numbers based on user input, and the output of the numbers were correctly calculated. I learned that there are many functions used in C and in C++ that have a specific job to perform when called on in the program, and I also learned that a function can be called from another function (in this case, the sum function was called from the main function).
I have discovered that using functions can sometimes be more practical, and can be a bit of a time saver when it comes to certain jobs that need to be performed. In the past, I have done a project on arithmetic operators, and writing the program to add, subtract, multiply, and divide numbers the user inputs can be much longer than just writing a function to perform the same job. I am sure this is not always the case, but in this particular example, it proved to be true. Also in my research, I learned that a function can perform its job independently from the program and does not need interference.
If you're doing an experiment instead of a retest, delete this section.
If you've opted to test the experiment of someone else, delete the experiment section and steps above; perform the following steps:
Whose existing experiment are you going to retest? Prove the URL, note the author, and restate their question.
Evaluate their resources and commentary. Answer the following questions:
State their experiment's hypothesis. Answer the following questions:
Follow the steps given to recreate the original experiment. Answer the following questions:
Publish the data you have gained from your performing of the experiment here.
Answer the following:
Answer the following: