Shane Swimley's Spring 2012 Opus
Description:Shane Swimley, Male, American
Pursuits: Win
Interests: Video Games, Movies, The NFL, Computing
As an aid, feel free to use the following questions to help you generate content for your entries:
In the first days of class concepts of significance that I have taken away from said learning are:
svn add and svn commit actions.
pointers, using pointers in C programming code.
integers, chars, using integers and chars as pointers, using integers and chars in C programming code.
include action, using include actions in C programming to use libraries.
The svn commands are great for saving information to your directories and committing changes.
The pointers are used to have something exist in memory but no be contained in a certain place.
The integers and chars can be used to declare variables.
The include action is used to reference pre-existing libraries contained in the C programming language.
Something that does not make perfect sense to me at this point in the class so far is the “%u\n” “%d\n” portions of code.
My challenge with a C programming course is that I have no previous experience with a programming language, a lot of new information to grasp.
With this in class example we used pointers, malloc, a while loop, if condition, else and else if condition, srand, time, NULL,
malloc was a call for an allocation of memory.
While loop with conditions was our implementation to keep the program running for more than one instance.
srand was our pseudo random number generator.
time was our value system of numbers that srand used to return random numbers? I think.
If I remember correctly when you NULL something you are acknowledging that it exists without physically or logically assigning it a specific value, out it's were the integer pointers input and pick.
We also talked about how it was difficult for a computer to be random without eventually becoming predictable in some way, due to the facts of the way a computer operates always following instructions, and not having the distinct ability to make a decision on it's own accord.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *input, *pick; input=pick=NULL; input=(int *)malloc(sizeof(int)*1); pick=(int *)malloc(sizeof(int)*1); *input=0; *pick=0; while(*pick !=-1) { srand(time(NULL)); *pick=rand()%99+1; printf("Guess the computer's pick: "); scanf("%d", input); if(*input==*pick) { printf("Congratulations you have won\n"); } else if(*input > *pick) { printf("Your guess was high\n"); } else { printf("Your guess was low\n"); } printf("Computer had %d\n", *pick); printf("0 to play again, -1 to quit\n"); scanf("%d", pick); } return(0);
}
With this class example we used new C/C++ components argc and argv
argc in C/C++ is the argument count within a programs pseudo code, we used the argument counter in this program to say that if the argument count was less than 2 the program would print a string message to the user telling them that need more arguments and how many arguments they actually provided.
argv is an abbreviation for an argument vector, we used argv as a double pointer character, that is really the best I can explain what this is doing at this point.
#include<stdio.h> #include<stdlib.h> int main(int argc, char **argv) { unsigned char i; if(argc<2) { printf("%8s must be run with 1 or more arguments, you only provided %hhu\n",(argc-1)); exit(1); } printf("You ran this program with %hhu arguments, they are:\n",(argc-1)); for(i=1;i<argc;i++) { printf("argv[%hhu]: %s\n",i,*(argv+i)); } return(0); }
I am adding all of the coded examples that we have done in class so far as my 4th opus entry. Probably add some textual content about what each program was focusing on once I get the format of the entry all setup with the all the examples included.
Example 1
#include <stdio.h> int main() { printf("an int is %u bytes\n", sizeof(int)); return(0); }
Example 2
#include <stdio.h> int main() { int a; a=0; printf("a contains %u\n", a); printf("a's address is 0x%x\n", &a); return(0); }
Addition to var2.c #include<stdio.h> int main() { int a=0; int *b; b=&a; *b=12; printf("a contains %u\n", a); printf("a's address is 0x%x\n", &a); printf("b contains %u\n, *b); printf("b points to 0x%x\n, b); printf("b's address is 0x%x\n",&b); return(0); }
Example 3
#include<stdio.h> int main() { int v=17; //setting the integer v equal to the number 17 int *p1=NULL; //setting the pointer p1 to NULL, NULL is allowing p1 to exist without assigning an exact value printf(“v is %u\n”, v); //having the computer display or “print out” the value of v p1=&v; printf(“*p1 is %u\n”, *p1); *p1=53; printf(“v is %u\n”, v); printf(“*p1 is %u\n”, *p1); v=7; printf(“v is %u\n”, v); printf(“*p1 is %u\n”, *p1); return(0); }
Example 4
#include<stdio.h> int main() { int num=0; printf(“Please enter an integer value: “); scanf(“%d”,&num); printf(“You just input %d\n”,num); if((num % 2) == 0) { printf(“It is even.\n”); } else { printf(“It is odd.\n”); } return(0); }
Example 5
#include<stdio.h> #include<stdlib.h> int main() { int *p1,*p2,**p4; p1=(int *)malloc(sizeof(int)*1); *p1=26; printf("*p1 is %u\n",*p1); p2=p1; p4=&p1; printf("**p4 is %u\n",**p4); printf("*p2 is %u\n",*p2); *p2=61; printf("*p1 is %u\n",*p1); printf("**p4 is %u\n",**p4); printf("*p2 is %u\n",*p2); **p4=16384; printf("*p1 is %u\n",*p1); printf("**p4 is %u\n",**p4); printf("*p2 is %u\n",*p2); return(0); }
Example 6
#include<stdio.h> #include<stdlib.h> int main() { int *input, *pick; input=pick=NULL; input=(int *)malloc(sizeof(int)*1); pick=(int *)malloc(sizeof(int)*1); *input=0; *pick=0; while(*pick !=-1) { srand(time(NULL)); *pick=rand()%99+1; printf("Guess the computer's pick: "); scanf("%d", input); if(*input==*pick) { printf("Congratulations you have won\n"); } else if(*input > *pick) { printf("Your guess was high\n"); } else { printf("Your guess was low\n"); } printf("Computer had %d\n", *pick); printf("0 to play again, -1 to quit\n"); scanf("%d", pick); } return(0); }
Example 7
#include<stdio.h> #include<stdlib.h> int main() { char *value,i; value=(char *)malloc(sizeof(char)*4); *(value+0)=0; *(value+1)=1; fprintf(stdout, "please enter a value (-128-+127):"); fscanf(stdin,"%hhd",&i); *(value+2)=i; *(value+3)=(2*i)+3; for(i=3;i>=0;i--) //(i=0;i<=3;i++) { printf("%hhd\n",*(value+i)); } return(0); }
Example Sample
#include<stdio.h> #include<stdlib.h> int main(int argc, char **argv) //parameters are in the ( ), first parameter of main must be an integer { unsigned char i; if(argc<2) { printf("%8s must be run with 1 or\ more arguments, you only provided %hhu\n",*(argv+0),(argc-1)); exit(1); // \ followed by enter allows you to continue code on new line } printf("You ran this program with %hhu arguments, they are:\n",(argc-1)); for(i=1;i<argc;i++) { printf("argv[%hhu]: %s\n",i,*(argv+i)); } return(0); }
Example FileFun
#include<stdio.h> #include<stdlib.h> int main() { FILE *in,*out; char value=0; in=fopen("file.txt","r"); out=fopen("out.txt","w"); if(in==NULL) { printf("ERROR!\n"); exit(1); } fscanf(in,"%hhd",&value); while(value != -1) { value*=2; fprintf(out,"%hhd\n",value); fscanf(in,"%hhd",&value); } fclose(in); fclose(out); return(0); }
Project 0 or as I like to call it range.c
#include <stdio.h> #include <math.h> int main() { // Variables unsigned long long int quantity = 0; unsigned char uc = 0; signed char sc = 0; unsigned short int usi = 0; signed short int ssi = 0; unsigned int ui = 0; signed int si = 0; unsigned long int uli = 0; signed long int sli = 0; unsigned long long int ulli = 0; signed long long int slli = 0; // Display information for unsigned char data type printf("An unsigned char is %d bytes\n", sizeof(uc)); printf("The range of an unsigned char is %hhu to %hhu\n", uc, (uc-1)); quantity = (unsigned char)(uc-1) + 1; // What does this line do? printf("An unsigned char can store %llu unique values\n\n", quantity); // Display information for signed char data type printf("A signed char is %d bytes\n", sizeof(sc)); quantity = (unsigned long long int)pow(2, (sizeof(sc)*8)); // What is happening? printf("The range of a signed char is %hhd to %hhd\n", (sc-(quantity/2)), (sc+(quantity/2)-1)); printf("A signed char can store %llu unique values\n\n", quantity); // Display information for unsigned short int data type printf("An unsigned short int is %d bytes\n", sizeof(usi)); printf("The range of an unsigned short int is %hhu to %hhu\n", usi, (usi-1)); quantity = (unsigned short int)(usi-1) + 1; // What does this line do? printf("An unsigned short int can store %llu unique values\n\n", quantity); // Display information for signed short int data type printf("A signed short int is %d bytes\n", sizeof(ssi)); quantity = (unsigned long long int)pow(2, (sizeof(ssi)*8)); // What is happening? printf("The range of a signed short int is %hhd to %hhd\n", (ssi-(quantity/2)), (ssi+(quantity/2)-1)); printf("A signed short int can store %llu unique values\n\n", quantity); // Display information for unsigned int data type printf("An unsigned int is %d bytes\n", sizeof(ui)); printf("The range of an unsigned int is %hhu to %hhu\n", ui, (ui-1)); quantity = (unsigned int)(ui-1) + 1; // What does this line do? printf("An unsigned int can store %llu unique values\n\n", quantity); // Display information for signed int data type printf("A signed int is %d bytes\n", sizeof(si)); quantity = (unsigned long long int)pow(2, (sizeof(si)*8)); // What is happening? printf("The range of a signed int is %hhd to %hhd\n", (si-(quantity/2)), (si+(quantity/2)-1)); printf("A signed int can store %llu unique values\n\n", quantity); // Display information for unsigned long int data type printf("An unsigned long int is %d bytes\n", sizeof(uli)); printf("The range of an unsigned long int is %hhu to %hhu\n", uli, (uli-1)); quantity = (unsigned long int)(uli-1) + 1; // What does this line do? printf("An unsigned long int can store %llu unique values\n\n", quantity); // Display information for signed long int data type printf("A signed long int is %d bytes\n", sizeof(sli)); quantity = (unsigned long long int)pow(2, (sizeof(sli)*8)); // What is happening? printf("The range of a signed long int is %hhd to %hhd\n", (sli-(quantity/2)), (sli+(quantity/2)-1)); printf("A signed long int can store %llu unique values\n\n", quantity); // Display information for unsigned long long int data type printf("An unsigned long long int is %d bytes\n", sizeof(ulli)); printf("The range of an unsigned long long int is %hhu to %hhu\n", ulli, (ulli-1)); quantity = (unsigned long long int)(ulli-1) + 1; // What does this line do? printf("An unsigned long long int can store %llu unique values\n\n", quantity); // Display information for signed long long int data type printf("A signed long long int is %d bytes\n", sizeof(slli)); quantity = (unsigned long long int)pow(2, (sizeof(slli)*8)); // What is happening? printf("The range of a signed long long int is %hhd to %hhd\n", (slli-(quantity/2)), (slli+(quantity/2)-1)); printf("A signed long long int can store %llu unique values\n\n", quantity); return(0); }
Project 1 or as I like to call it Project2.c and Project2.1.c
#include<stdio.h> #include<stdlib.h> int main() { FILE *message, *key, *cipher; char c, fname[] = "message.txt"; char code[] = "key.txt"; int keyvalue; message = fopen(fname, "r"); key = fopen(code, "r"); cipher = fopen("cipher.txt", "w"); c = fgetc(message); fscanf(key,"%d",&keyvalue); printf("Message is: "); while(c != EOF) { fprintf(stdout, "%c", c); c = fgetc(message); } fclose(message); message = fopen(fname, "r"); c = fgetc(message); printf("Cipher is: "); while(c != EOF) { if((c >= 65) && (c <= 'Z')) c = c + keyvalue; else if((c >= 'a') && (c <= 'z')) c = c + keyvalue; fprintf(stdout, "%c", c); fprintf(cipher, "%c", c); c = fgetc(message); } fclose(message); fclose(key); return(0); }
#include<stdio.h> #include<stdlib.h> int main() { FILE *cipher, *key, *decipher; char c, fname[] = "cipher.txt"; char code[] = "key.txt"; int keyvalue; cipher = fopen(fname, "r"); key = fopen(code, "r"); decipher = fopen("decipher.txt", "w"); c = fgetc(cipher); fscanf(key,"%d",&keyvalue); printf("Cipher is: "); while(c != EOF) { fprintf(stdout, "%c", c); c = fgetc(cipher); } fclose(cipher); cipher = fopen(fname, "r"); c = fgetc(cipher); printf("Decipher is: "); while(c != EOF) { if((c >= 65) && (c <= 'Z')) c = c - keyvalue; else if((c >= 'a') && (c <= 'z')) c = c - keyvalue; fprintf(stdout, "%c", c); fprintf(decipher, "%c", c); c = fgetc(cipher); } fclose(cipher); fclose(key); return(0); }
Standard I/O (STDIO, STDOUT, STDERR).
Standard I/O stands for the Standard Input and Output, standard input devices are commonly keyboards or mice, etc… standard outputs are monitors, printers, etc…
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 */ while(c != EOF) { if((c >= 65) && (c <= 'Z')) c = c - keyvalue; else if((c >= 'a') && (c <= 'z')) c = c - keyvalue; fprintf(stdout, "%c", c);
Pointers (address of, assignment, dereferencing)
Pointers are used to reference information, you would use a pointer to not directly place something but to reference multiple “things” to that location via a pointer.
Pointers are indicated with * symbol, pointers can contain more than one * as in ,*, and so on….
The * in a pointer is usually followed by a defining word or phrase or character, in my example listed I have *cipher, *key, and *decipher
The *cipher is a pointer to cipher and not actually cipher.
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> #include<stdlib.h> int main() { FILE *cipher, *key, *decipher;
Arithmetic (equations, operators)
Mathematical logic that is used in pseudo codes syntax (IE: +,-,/,x,>,<,=,==,!
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:
while(c != EOF) { if((c >= 65) && (c <= 'Z')) c = c + keyvalue; else if((c >= 'a') && (c <= 'z')) c = c + keyvalue;
Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)
series list of memory values linked by a common name and data type.
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() { num someVals[3]=25,44,22 return(0); }
Header Files (Local and System), C Standard Library (Libc), Libraries
Collection of predefined functions and syntax that can loaded as a library header file.
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> #include<stdlib.h> #include<math.h> #include<string.h> int main() { return(0); }
File Access (Read, Write, Append)
The File Access of a File determines the privileges the user has with the file upon opening said file, whether it be just being able to read, or read and write a new file, or append and add to an existing file(s)
Demonstration of the chosen keyword.
I believe that when you are trying to add or deny file access you would as follows
+r to allow reading, -r to not allow read
+w to write, -w to not allow writing
+a to allow appending, and -a to not…
logic and operators (and, or, not, xor)
logic operators like and, or, not, xor compare expressions, Boolean expressions in particular, they are also used to compare two expressions or sentences.
Demonstration of the chosen keyword.
x = Not 23 > 12 ' x equals False. x = Not 23 > 67 ' x equals True.
Variables (types, ranges, sizes)
variables are identifiers that create a permanent “existence” the variable could be named anything from the letter x to the name Shane.
their are different types of variables that are pre-determined the c language for size allocation purposes; like:( char, int, long int…so on)
Demonstration of the chosen keyword.
unsigned long long int quantity = 0; unsigned char uc = 0; signed char sc = 0; unsigned short int usi = 0; signed short int ssi = 0; unsigned int ui = 0; signed int si = 0; unsigned long int uli = 0; signed long int sli = 0; unsigned long long int ulli = 0; signed long long int slli = 0;
To learn the programming languages c and c++?
variables, pointers, classes, code, arrays, logic operators, math, header files…
I will try my best and reflect that effort on a grade based system administered from professors.
I don't really know much about this coming into this class but I know much more then I did, I can't really say that amounts to anything impressive to someone that does this for a living but I could probably hold a common conversation on the topic now.
I probably could have learned more if I wasn't taking 4 other classes that were all full of brand new information at the same time, but ya know.
yes.
sure?
again sure?
I would try some simpler things for people that have no idea what is going on, and have been looking at this subject of study for the first time with this class.
What will happen if I take the ; off the end of a statement and try to compile the program.
lab46
Based on what I have learned thus far about c programming I think there would be an error in trying to compile the program.
I believe it would be considered a syntax error and the would be the reason there would be an error in trying to compile.
I am going to experiment on a hello world program we wrote in class this semester on lab46
lab46:~$ nano hello.c lab46:~$ gcc -o hello hello.c hello.c: In function 'main': hello.c:5: error: expected ';' before 'return' lab46:~$
Based on the data collected:
yeah I am pretty good.
it was applicable
no sir.
intelligence.
data is good.
make sure you put ; at the end of applicable statements.
What happens if you do not include a return; at the end of your program/function.
lab46
I am not entirely sure I am assuming I will get some sort of syntax error but to be sure I will have to run it to find out.
I am going to use my hello world! program once again that is deployed on lab46
lab46:~$ nano hello.c lab46:~$ gcc -o hello hello.c lab46:~$ nano hello.c lab46:~$ ./hello Hello, World!
Based on the data collected:
No sadly I was wrong the program still ran and now I feel foolish.
it was.
apparently :O
intelligence.
none.
The program still ran and complied with the return; statement line removed.
I am going to attempt to add the multiplication portion of project 2 into project 2.
I used the other functions addition and subtraction that I had help writing, more so addition because I figured add and multiply are alike in common sense than subtraction.
The goal is that it will work in the program just the way the other functions do and multiply my 4 digit numbers correctly. oh yeah and compile. hopefully.
I wrote the code (at least it seems like working code to me) into the program and I will attempt to compile it and run it on lab46
lab46:~/src/cprog$ nano bignum.c lab46:~/src/cprog$ gcc -o bignum bignum.c lab46:~/src/cprog$ ./bignum How many digits are in your largest number? 4 Please enter 1 to Add, 2 to Subtract, 3 to Multiply, 4 to Divide 3 Enter your first number 0010 Please enter your second number 0010 01870 lab46:~/src/cprog$
Based on the data collected:
no it was not my program told me 10×10 = 1870
it was.
i have no idea.
knowledge of how to program
the intended answer.
I did not get the correct answer, I will have to figure it again a better way that produces the intended answer.
The fact that I can not figure out how to use atoi has led me to use this opus entry on Type Conversions.
The C Programming Language 2nd edition by Kernighan and Ritchie says
“When an operator has operands of different types, they are converted to a common type according to a small number of rules. In general the only automatic conversions are those that convert a “narrower” operand into a “wider” one without loosing any information… A char is just a small integer, so chars may be freely used in arithmetic expressions. This permits considerable flexibility in certain kinds of character transformations. One is exemplified by this naive implementation of the function atoi, which converts a string of digits into its numeric equivalent.”
/* atoi: convert s to integer */ int atoi(char s[]) { int i, n; n = 0; for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i) n = 10 + n + (s[i] - '0'); return n; }
That is all I really read and found in the book/index that specifically talked about the atoi function.
C Pocket Reference by Prinz & Kirch-Prinz
Conversion Between Strings and Numbers
“A variety of functions are declared in the header file stdlib.h to obtain numerical interpretations of the initial digit characters in a string. The resulting number is the return value of the function.”
int atoi( const char *s ); /*Interprets the contents of the string s as a number with type int. The analogous functions atol(), atoll()(*), and atof() are used to convert a string into a number with type long, long long(*), or double.*/
And that is pretty much what that book had to say about my problem so I guess I will go ahead and try to work on implementing this into my project bignum.c
for(x = digit1; x >= 0; x--) { *(result+x) = *(value1+x) + *(value2+x) + *(result+x); if(*(result+x) > 9) { *(result+x) = *(result+x) - 10; *(result+x - 1) = *(result+x - 1) + 1; } }
For this opus entry I am going to try and re-break down what Matt went over with me in the last class session.
The first line of the for loop in the the code block above is stating:
for the instance that the variable x equals the int digit1 and also the variable x is greater than or equal to zero decrement x by 1.
*(result+x) = *(value1+x) + *(value2+x) + *(result+x);
This line is saying that the pointer of result+x is equal to the pointer of value1+x plus the pointer of value2+x plus the pointer of result+x which has been zeroed out for the program.
if(*(result+x) > 9)
The if statement is creating a condition that if the pointer of result+x is greater than the number 9 to go on and do what other instructions are in the if statement.
{ *(result+x) = *(result+x) - 10; *(result+x - 1) = *(result+x - 1) + 1; }
Inside of the if statement as the code shown above is saying process this code when the if statement is true.
Take the current result x variable you are working with and subtract 10 and take the next result x variable to the left and add 1 to it.
Inheritance in object-oriented programming is a way to use code that you have previously included in a class, usually refered to as parent classes, base classes, or a superclasses. The new classes that are inheriting the base class are commonly refered to as child classes or subclasses and or derived classes.
#ifndef _RECTANGLE_H #define _RECTANGLE_H #include "shape.h" class rectangle: public shape{ public: virtual int perimeter(); virtual int area(); }; #endif
As shown in the code block example above this file called rectangle.h would be inheriting the public classes code from the file shape.h making the parent file shape.h and the child file rectangle.h
Class inheritance has three different types of data:
Public:
Any other files in your inheritance tree that include the header files needed to use those public variables of the class you are trying to access can.
Protected:
Only a child file of the parent can use protected files, if a child is not directly pointed to the parent file they are trying to access protected data from that child file will not be able to access the protected portion of that code.
Private:
Private variables are only accessable by the class they are defined in, although they can be accessed through a call to a protected or public variable in the same class that has access.
The GNU Compiler Collection or (GCC) is a programming code compiler, a compiler is an application that uses source code written in a programming language and creates object code to have an executable program from the source code.
The languages the compiler can compile that we deal with in our class are C (gcc) and C++ (g++)
The compiler consists of a front-end and back-end
The front-end of the compiler handles the programming language setting up the information to be handled by the back-end
The back-end deals with converting the language into the specific target architecture
Scope (Block, Local, Global, File)
Global Scope is defined outside of specific functions in the head section of a program and is usually accessible by the entire program.
File Scopes act about the same as Global scopes with the exception that the global scope is accessible by the whole program and the file scope is just accessible in that particular FILE.
Local Scope is defined within a specific function and is usually just relevant to that function and would not be recognized by another function it was not part of.
Block Scope is defined within a specific code block
{ Block Scope }
Demonstration of the chosen keyword.
int x = 1; // global variable 12 13 int main() 14 { 15 int x = 5; // local variable to main 16 17 cout << "local x in main's outer scope is " << x << endl; 18 19 { // start new scope 20 int x = 7; // hides x in outer scope 21 22 cout << "local x in main's inner scope is " << x << endl; 23 } // end new scope
Type Casting
Type Casting happens when you have a given expression and you convert or assign that expression another type.
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:
short a=2000; int b; b=a;
Selection Structures (if, case/switch)
An If selection structure is dependent on a condition statement, for example if something is true do this OR if something is false do this other thing.
A switch case selection structure is a shorter substitute to long if statements, a value variable is compared and or switched in each of the following cases for the programs structure.
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:
switch ( <variable> ) { case this-value: Code to execute if <variable> == this-value break; case that-value: Code to execute if <variable> == that-value break; ... default: Code to execute if <variable> does not equal the value following any of the cases break; }
Repetition/Iteration Structures (for, while, do while)
The repetition structure of a while loop allows for a statements execution to run repeatedly until the condition of that loop has been met.
The do while loop has the same structure as the while loop with the exception that do while loop tests the condition at the end of the loop structure so that the statement will be executed at least once.
The for loop handles all ( variable initialisation; loop condition; variable update ) in the same set of paraenteses.
Demonstration of the chosen keyword.
while LOOP
/* * Sample code block */ #include <stdio.h> int main() { int count = 0; while(count < 10) { printf("%d\n", count); ++count; } return 0; }
Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:
Sample output: 0 1 2 3 4 5 6 7 8 9
Structures (Declaration, Accessing Elements, Pointers to)
Structure Declarations are declared by the preset struct then followed by a variable name in c programming.
When accessing elements of a structure you need to call both the name of the struct and the variable name of the struct to access the individual elements.
You can also your Pointers to access elements inside of structs by declaring the pointer and implementing it to a global variable.
/* * Sample code block */ #include <stdio.h> int main() { struct thisclass{ int something } return(0); }
typedef, enum, union
While structures define several fields data types a UNION is only used to define one location that may be addressed by different names.
type def gives you the ability to name and define your own variables with the use of a typedef statement.
enumerated data - used for variables that may only contain a set number of values, the variables are then referenced by the name or (tag).
typedef example
/* * Sample code block */ #include <stdio.h> int main() { 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; /* Now to use it */ day_of_the_week today = TUESDAY; return(0); }
enum example
/* * Sample code block */ #include <stdio.h> int main() { enum day_of_the_week {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,FRIDAY, SATURDAY}; /* Now use it */ enum day_of_the_week today = TUESDAY; return(0); }
Functions, Parameters (Pass by: Value, Address, Reference), Return Types, Recursion, Command-line arguments
Functions are sets of statements that contains three main parts a function header, function body and function prototypes functions can also be called on by a program from outside of that function.
Parameters are values within the functions.
When you pass a parameter by Reference you are changing the value of the parameter when you pass it.
When you pass the parameter by Value you are not changing the parameter just passing it along.
Command-Line Arguments are used for retrieving parameters entered by the user when using your program.
The Return Type is the syntax and definitions of values returned from a function.
Recursion is when a function can call on itself with out an acting outside call.
Functions
int main() { ... }
Recursion
int factorial(int n) { if(n == 1 || n == 0) { return 1; } else { return n*factorial(n-1); } }
Parameters
int main { fctn(num1, 12); } void fctn(int arg1, int arg2) { ... }
Compiler, Preprocessor, Flags, Assembler, Linker, Multi-file programs (how to structure, how to compile)
The Compiler is the actual piece of software that turns your code into an executable.
The Preprocessor allows for your programs to include header files, macro expansions and conditional compilation.
Flags are used to optimize how you want to compile the code for example -wall -o etc…
An assembler takes source code to produce machine code.
A Linker takes the compiler's object files and puts them all together so the computer recognizes the files and runs them together as a program.
to learn how to become and effective programmer in the languages of c and c++
syntax
indenting format
compiling
functions
classes
Libraries
Header Files
Pointers
Arrays
etc…
Well from knowing zero day 1 I now know more than zero.
followed.
Reflect upon your results of the measurement to ascertain your achievement of the particular course objective.
ok.
of course.
not sure.
n/a
more beginner focus.
What will happen if you do not include the \n at the end of a printf statement.
lab46
I am thinking that without the \n the printf statement will not display.
State your rationale. I am pretty sure \n is a terminator for the printf statement.
I am going to test my hypothesis on lab46 with my hello.c program.
lab46:~$ nano hello.c lab46:~$ gcc -o hello hello.c lab46:~$ ./hello Hello, World!lab46:~$
Based on the data collected:
No.
it was applicable.
No.
I guessed wrong.
None.
The program still complied and ran without the \n at the end of my printf statement but as you can see the command prompt ended up on the same line that the program executed the printf on.
So the \n is a line terminator and not a printf function terminator if that makes sense in the best of my ability to explain what I am experimenting.
For this experiment I will be seeing what will happen if the program does not include a main function and just includes statements.
Like this.
#include <stdio.h> { printf("Hello, World!\n"); return(0); }
Lab46
I am not sure what will happen I am assuming the program will not compile or function properly.
State your rationale.
I am thinking that the program needs a Function structure of some sort to run properly.
going to test this on lab46
lab46:~$ gcc -o hello hello.c hello.c:3: error: expected identifier or '(' before '{' token
Based on the data collected:
Yeah I believe this time it was I did get an error for an expected identifier.
it was applicable.
No I think the identifier the program is looking for is the main function.
None.
None.
The program did not compile when the line of
int main()
was removed from the program I am not 100% sure if it was asking for a function container, okay well i just did this experiment to test it further.
#include <stdio.h> main() { printf("Hello, World!\n"); return(0); }
and the program ran and compiled so the int was not necessary it was looking for a main() function or a function container in general I am guessing. Not sure if it has to named main() but that sounds like another experiment.
Perform the following steps:
Whose existing experiment are you going to retest? Provide 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:
Wanted to revisit structs and unions from a class we had this semester.
When creating a struct you are making a record for a set of labelled objects into a single structured object.
Example:
struct sales { int month sales; char *item_name; char *item_type; float totals; };
This is an example of a struct declaration, which is a list of fields that can contain any types (int, char, etc…) and allocates a total amount of storage based on the sum requirements for all of the list types included, along with any internal padding.
A union is nearly the same as a struct except for the way a union allocates memory, each data type in the union starts from the same location in memory instead of having its own location like in a struct.
The concept of a union is to save space the multiple data types inside the union are being condensed into the same memory location.
Example:
union <name> { <datatype> <1st variable name>; <datatype> <2nd variable name>; . . . <datatype> <nth variable name>; } <union variable name>;
Since we talked about inheritance at length this semester I will refresh on that with this journal entry.
Inheritance in programing has to do with the way classes relate to each other, for example there are two main types of classes in respect to programming inheritance parent classes and child/children classes.
Parent classes are the preceding classes that came before their children a lot like it would seem. Parent classes are also sometimes called superclasses, ancestor classes or base classes.
Child classes or subclasses are derived from their parent class and live in a hierarchy based system.
The application of using inheritance in programming is to relate two or more classes together.
Figured I would write this opus entry on Header Files since that seems to be one of the thing I do grasp.
There are a few different instances of header files
There is the standard Library of header files which are already made files saved that included commonly used declarations that a program might need, for instance stdio.h which includes common input and output functions used in c programming and stdlib.h which includes standard collection of functions collected into a library file.
There are also header files that you can make on your own for instance if you wrote a function saved it and then included it in another function as a .h file that program will now use all the logic from the other instance your wrote with just the file included at the start of the new file as a .h file.
Just going to scribble some things down here for the last entry as I go through some of the programs we accomplished in class this semester.
int main ( ) anything inside the parenthesis are parameters for main and the first parameter of main must be an integer. when on a line of code if you type a \ followed by enter the syntax is that the line will continue onto the next line below it but the program will read it as a single line of code even though for your viewing pleasure its broken up into more than one line of text. int sum(int, int, int, int); is a function prototype.
and so on…
I/O Streams (cin, cout, cerr, stream operators) [C++]
I/O Streams in C++ is an standard included library, the library consists of (basic class templates, class template instantiations, standard objects, types, and manipulators).
cin - is an object of the class of istream that notates the standard input stream, corresponding to cstdio stream. cin like most systems defaults its standard input from the keyboard.
cout - is an object of the class of ostream that notates the standard output stream, corresponding to cstdio stream.
cerr - is the standard output stream for errors.
Namespaces [C++]
Namespaces give groups like classes and functions a more global scope, for instance if you had two int's in your program but you wanted each to have its own global scope you could name one namespace first and the other namespace second like in the example shown below.
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:
// using #include <iostream> using namespace std; namespace first { int x = 5; int y = 10; } namespace second { double x = 3.1416; double y = 2.7183; } int main () { using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0; }
Type Casting Operators, Const-Volatility Specifiers (const, volatile) [C++]
casting operators remove c syntax inherent for the purpose of making the types more compatible with c++, there are several casting operators.
dynamic_cast - conversion of polymorphic types.
static_cast - conversion of non polymorphic types.
const_cast - removes the const, volatile, and _unaligned attributes
reinterpret_cast - simple reinterpretation of bits.
safe_cast - produce verifiable MSIL.
Classes (Objects, Constructor, Destructor, Access Control, Public, Protected, Private, Friend, “this” pointer) [C++]
A class allows you to put functions inside of a data structure for the purpose of organization and ease of use.
A constructor is a function that can be included within a class that can be automatically called whenever a new object is created within that class for the reason of avoiding returning unexpected values.
Destructors are called automatically when an object is destroyed with the purpose of releasing previously allocated memory.
Access Control breaks down into the Public, Protected, and Private data type sub class definitions.
Public variables and data types are accessible to the program outside of the class
Protected are accessible but may not be changed
Private variables and data types are only available inside that specific class they are defined in and may not be acted upon by the outside program.
this pointer can only be used as a nonstatic member function of a class, struct, or union.
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:
class example{ public: int a; int b; int c; int d; private: int e; int f; protected: int g; };
Inheritance (single, multiple Inheritance), Polymorphism/Virtual Functions, Abstract Base Class [C++]
Inheritance in object oriented programming is used to create a relationship between two or more classes.
when using single class inheritance it means pretty much what it sounds like a sub class can only inherit from one super class or parent class.
and obviously multiple inheritance means that you can inherit information in your subclasses from more than one parent class.
Polymorphism with pointers using the ability that a pointer to a derived class is then compatible with a pointer to it's base class also.
Virtual members or functions are members of a class that can be changed in a derived class.
An abstract class is designed to be a base class that contains a pure virtual function.
class A { public: void DoSomethingALike() const {} }; class B : public A { public: void DoSomethingBLike() const {} }; void UseAnA(A const& some_A) { some_A.DoSomethingALike(); } void SomeFunc() { B b; UseAnA(b); // b can be substituted for an A. }
Overloading (Functions, Operators) [C++]
Overloading means that you are assigning more than one name for the same function or operator in the same scope.
Example I found showing Function Overloading.
#include <iostream> using namespace std; 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; } int main() { print(10); print(10.10); print("ten"); }
Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:
Here is int 10 Here is float 10.1 Here is char* ten
Exception Handing (throw, try, catch) [C++]
An exception in programming is when a program has a situation that has an unexpected circumstance that happens in that section of the programs code. To handle these exceptions their are programming keywords in place like (throw, try, and catch).
catch is used as a preemptive guard against exceptions.
throw is used as a handler after and exception has occurred and tells the program to get rid of or throw the bad segment or unexpected circumstance for the section of code.
try is used as a handler for after an exception is realized as well and instead just telling the program to toss the bad line or code out it gives an instance of instead to try.
Templates, STL (Standard Template Library) [C++]
The Standard Template Library is made of predefined class for C++ and provides components called algorithms, containers, functional, and iterators.
I already filled this out twice
What will happen if i replace a for loop with a while loop in my program. as shown here
#include<stdio.h> #include<stdlib.h> int main(int argc, char **argv) //parameters are in the ( ), first parameter of main must be an integer { unsigned char i; if(argc<2) { printf("%8s must be run with 1 or\ more arguments, you only provided %hhu\n",*(argv+0),(argc-1)); exit(1); // \ followed by enter allows you to continue code on new line } printf("You ran this program with %hhu arguments, they are:\n",(argc-1)); for(i=1;i<argc;i++) { printf("argv[%hhu]: %s\n",i,*(argv+i)); } return(0); }
I am going to replace the for loop in this program with a while loop and see what happens.
lab46
I do not have a clue what it will do. My best guess is break something.
State your rationale.
Seems like something that would break something.
lab46
lab46:~/src/cprog$ nano sample1.c lab46:~/src/cprog$ gcc -o sample1 sample1.c sample1.c: In function 'main': sample1.c:15: error: expected ')' before ';' token
Based on the data collected:
Yep it broke
it was
no I think it just produces a syntax error
none
none
I broke the program you can not just simply make a for loop a while loop
I am going to try and add a simple multiplication function to the file sample2.c where we had 4 int declared and the program calculating a sum and average.
lab46
#include<stdio.h> #include<stdlib.h> int sum(int,int,int,int); //function prototype int average(int,int,int,int); int main() { int a,b,c,d; int avg; a=b=c=d=0; avg=0; printf("Enter first value: "); fscanf(stdin, "%d",&a); printf("Enter second value: "); fscanf(stdin, "%d",&b); printf("Enter third value: "); fscanf(stdin, "%d",&c); printf("Enter fourth value: "); fscanf(stdin, "%d",&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:%d\n",a,b,c,d,average(a,b,c,d)); return(0); } int sum(int n1, int n2, int n3, int n4) { int total=0; total=n1+n2+n3+n4; return(total); } int average(int n1, int n2, int n3, int n4) { int average=0; average=(n1+n2+n3+n4)/4; return(average); }
I am going to try and follow the code above and add a similar instance for multiplication to see if i can get it to work I assume this will be easier than project 2's concept.
State your rationale. project 2 was dealing with specific allocated 4 digit numbers and something like that i don't know this just looks like it is going to make more sense to me and maybe work.
lab46
lab46:~/src/cprog$ nano sample2.c lab46:~/src/cprog$ gcc -o sample2 sample2.c lab46:~/src/cprog$ ./sample2 Enter first value: 2 Enter second value: 2 Enter third value: 2 Enter fourth value: 2 the sum of 2, 2, 2, and 2 is:8 the average of 2, 2, 2, and 2 is:2 the product of 2, 2, 2, and 2 is:16 lab46:~/src/cprog$
Based on the data collected:
Yeah it worked amazingly.
for once yes.
no
no
no
It worked I am pretty much pro.
Perform the following steps:
Whose existing experiment are you going to retest? Provide 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: