User Tools

Site Tools


opus:fall2011:rrichar8:part1

Part 1

Entries

September 10, 2011

  • Today is my first attempt at updating and editing my Opus
  • I've used a couple of links on the INTRODUCTION paragraph to see if they work. THEY DO !!!
  • Trying to figure out exactly what is required in this course, I've been a pest so far bugging Matt for information
  • Hope to start on the PROJECTS phase of this course today (9/10) or at least by Sunday (9/11)
  • I also hope I'm not the only one who is just getting started with this !!!!

September 15, 2011

  • I am beginning to compile the background information needed for my first project.
  • My first project will be a very simple program to display a name.
  • My second project will be to create a Number Base Conversion program.
  • Creating a Number Base Conversion program that has quite a few lines of code.
  • Taking a program that was written originally in Small Basic and trying to covert it into C++ language.
  • There are many commands that I will need to address to make this project work properly.
  • The greatest challenge is finding the right information sources to do this project correctly.
  • Using information from the Lab Site, the course books and the internet to accomplish this task.

September 22, 2011

Working on the RANGE project today. Acquainting myself with C syntax and entering code into the text editor on PUTTY. As an aid, feel free to use the following questions to help you generate content for your entries:

  • Entered data into the nano text editor.
  • Compiled and executed program properly after many attempts previously that ended in error messages.
  • What concepts are you dealing with that may not make perfect sense? Data input symbols and syntax are still confusing.
  • Trying to make sure I understand what exactly is required to complete an assigned task.

September 28, 2001

KEYWORDS:

  • Working on Keywords today, including: Standard I/O, Header Files, arithmetic, command line arguments, and others.
  • This is significant because it gives me a good chance to understand what they mean and how they are used.
  • What challenges are you facing with respect to the course? Trying to find the right information sources.
  • Using sources found in the text book, on the Wiki and on the Web.
  • Trying to find good examples to use with each keyword is another challenge.

Topics

Standard I/O (STDIO, STDOUT, STDERR)

STANDARD INPUT and OUTPUT STREAMS

stdin for (standard input),
stdout for (standard output),
stderr for (standard error).

stdio.h - standard buffered input/output, the I/O system:
#include <stdio.h>

stdin

  File pointer for standard input stream. Automatically opened when program execution begins.
  Example - scanf("%d", &val);

stdout

  File pointer for standard output stream. Automatically opened when program execution begins.
  Example - printf("Hello World");

stderr

  File pointer for standard error stream. Automatically opened when program execution begins.
  Example - fprintf(stderr, "Can't open input file\n");

STANDARD INPUT is normally associated with the keyboard and STANDARD OUTPUT with the screen, unless redirection is used. STANDARD ERROR is where you display error messages. Standard error is normally associated with the same place as standard output; Redirecting standard output does not redirect standard error.

Header Files (Local and System)

Header files define functions, constants and data types to use in your program, and are also used for declaring constants, data types and any other data that will be shared amongst multiple implementation files.

Using the #include <filename.h> format, such as:
#include <iostream>
#include <stdio.h>
#include <math.h>

In C, the usual convention is to give header files names that end with .h.
Here are some of the most common header files names and what they represent:

assert.h - Defines the assert() macro
ctype.h - Character handling
errno.h - Error reporting
limits.h - dependent limits
locale.h - Localization
math.h - math library
setjmp.h - Nonlocal jumps
signal.h - Signal handling
stdarg.h - Variable argument lists
stddef.h - Constants
stdio.h -I/O system
stdlib.h - Miscellaneous declarations
string.h - string functions
time.h -system time functions

arithmetic (equations, operators)

Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations.

Types of operators available in C are as follows:

  Arithmetic
  Assignment
  Logical/relational
  Bitwise

Arithmetic Operators

  + For performing Addition
  - For performing Subtraction
  / For performing Division
  * For performing Multiplication
  % Modulo for finding remainder in division operation
  -- Decrement (post and pre)
  ++ Increment (post and pre)

Assignment Operators

  =
  *= Multiply
  /= Divide
  %= Modulus
  += Add
  -= Subtract )

Logical / Relational Operators

  == Equal to
  != Not Equal to
  > Greater than
  < Less than
  >= Greater than or equal to
  <= Less than or equal to
  && Logical AND
  || Logical OR
  ! Logical NOT

Bitwise Operators

  & AND
  | Inclusive OR
  ^ Exclusive OR
  << Shift Left
  >> Shift Right
  ~ One's compliment 
  

int a = 6, b = -3, c = 2;
c= a - b * (a + c * 2) + a / 2 * b;
printf(“Value of c = %d \n”, c);

Command-line arguments

The command line is that it consists of a sequence of words, typically separated by whitespace.
Your main program can receive these words as an array of strings, one word per string.
The integer, argc is the argument count.
It is the number of arguments passed into the program from the command line, including the name of the program.
Command-line arguments are given after the name of a program in command-line operating systems.

#include <stdio.h>

int main ( int argc, char *argv[] )

Variables (types, ranges, sizes)

Variables in C are memory locations that are given names and can be assigned values. Variables are used to store data in memory for later use.

There are 2 basic kinds of variables in C which are numeric and character.

Numeric variables can either be integer values or they can be Real values. Integer values are whole numbers without a fraction part or decimal point in them. Real numbers can have a decimal point in them.

Character variables are letters of the alphabet as well as all characters on the ASCII chart and even the numbers 0 - 9. Characters must always be put between single quotes. A number put between single quotes is not the same thing as a number without them.

To declare a variable, first put in the type of variable and then give the variable a name.
Variables should be declared at the top before any other commands are used.

The difference between signed and unsigned variables is that signed variables can be either negative or positive but unsigned variables can only be positive. By using an unsigned variable you can increase the maximum positive range.

When you declare a variable, it is automatically considered a signed variable unless you declare it as an unsigned variable, you may use the word signed if desired. To declare it as an unsigned variable you must put the word unsigned before your variable declaration.

int - Numeric - Integer (-32,768 to 32,767)
short - Numeric - Integer (-32,768 to 32,767)
long - Numeric - Integer (-2,147,483,648 to 2,147,483,647)
float - Numeric - Real 1.2 X 10-38 to 3.4 X 1038
double - Numeric - Real 2.2 X 10-308 to 1.8 X 10308
char - Character All ASCII characters

#include <stdio.h>
 
int main()
{
   unsigned int a;
   signed int b;
   return 0;
} 

“String”, Format/Formatted Text String

Strings in C are represented by arrays of characters. String literals are words surrounded by double quotation marks.
Strings must have a 0 or null character after the last character to show where the string ends. The null character is not included in the string.
In a character array, create an array of chars and set each element in the array to a char value that makes up the string. When sizing the string array you need to add plus one to the actual size of the string to make space for the null terminating character, “\0”

Declaring String

As in string definition, we have two ways to declare a string. The first way is, we declare an array of characters as follows:
For example, the following defines a string of 50 characters:
char name[50];

And in the second way, we declare a string as a pointer point to characters:
char* s = “string”;

Use %s when printing the string.

File Access (Read, Write, Append)

Opening & Closing Files
Opening a file is handled using the system function fopen().
The basic command used to open a file is:
FILE * fopen(char * filename, char * mode)

File-Access Modes
Normal Access
r Open existing file for reading
w Open file for writing, destroying the contents; create if necessary
a Append at end of file; create if necessary
Update Access (for fixed-length records)
r+ Open existing file for reading & writing
w+ Open file for reading and writing, destroying the contents
a+ Open file for reading & writing – all writing is appended to the end of the file

Pointers (address of, assignment, dereferencing)

A pointer stores a reference to another value. A pointer is a memory address. Its location in memory is called its address.
Any direct assignment to a pointer variable will change the address in the variable, not the value at that address.
The assignment operation '=' between two pointers makes them point to the same pointee.
The “dereference” operation follows a pointer's reference to get the value of its pointee.
The dereference operator looks up the value that exists at that address.

A pointer type in C is the pointee type followed by a asterisk (*)
The asterisk (*) tells the compiler the variable is actually pointing to the data type and is not actually the data type.
Such as:
int* type: pointer to int
float* type: pointer to float

Type Casting

Typecasting is making a variable of one type, such as an int, act like another type, a char, in one single operation.
Put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable.
One use of typecasts is to force the correct type of mathematical operation to take place.
Typecasting is used in arithmetic operation to get correct result.
This is often needed in case of division when integer gets divided and the remainder is omitted.

  float a;
  a=10/3;
  printf("%f\n",a);

In the above code, replacing the line a=10/3; with a=(float)10/3;
produces 3.33333 as the result because 10 is converted to a floating point value before the division. See below:

  float a;
  a=(float)10/3
  printf("%f\n",a);

Selection Structures (if, case/switch)

Selection structures are used to change the flow of program execution.
It is achieved by establishing the truth or falsity of an expression (condition).

There are three basic types of selection structure that can be implemented

The if selection statement, if else selection statement and switch selection statement.

If is used when you want a single or a group of statements to be executed if the condition is true.
If the condition is false,
the statement is skipped and program continues by executing the first statement after the if selection structure.
It is possible to have if within an if statement. The if within an if statement is called nested if.

In the if else selection structure, the else statement will be executed when the condition is false.

In the switch statement, it allows you to select one from multiple options.
The switch selection structure consists of a series of a case label and an optional default case.
The switch statement works by comparing the value of the variable or expression within parentheses
with values specified in each case.
If there is a match, the statements following the case will be executed.
If there is no match, the default statement is executed.
At the end of each case,
the keyword break must be placed to exit from the switch immediately after statements execution.
Unlike the if statement, the switch case only executes outcomes when the variable matches one of the cases.

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

To execute a sequence of instructions repeatedly, while a condition is true, or until a condition becomes true,
is referred to as Iteration.
Repetition of statements with in program is referred to as a loop.
Looping in a program is the process of executing series of instructions repeatedly until a certain condition is met.
If statements can be nested within a loop.

Three types of repetition structure are the while loop, do while loop and for loop.

The while loop repeats of a set of instructions as long as the condition remains true. When the condition becomes false,
the repetition terminates and the first statement after the repetition structure is executed.

The do while loop is similar to the while loop.
The do while tests the loop condition at the end of the loop structure or after the body of the loop is executed.
The do while loop is a compound statement that must be performed at least ONE TIME.
The while part of the condition statement is tested and if it is true,
it will go back up to the beginning and the body of the do while loop will be executed again.
This will continue until the while part of the condition is false.

The for statement handles all the details such as variable initialization,
variable update and loop condition within single parentheses.
The for loop loops from one number to another number and increases by a specified value each time.
The basic for statement includes:
for ( variable initialization; loop condition; variable update )
When using the for statement, programmers should be careful to choose a condition that is guaranteed to
terminate the loop at some point in time, or face the risk of incurring in a so-called infinite loop.

Arrays (standard notation, pointer arithmetic)

An array is a set of consecutive memory locations that are used to store the same types of data.
An array is a collection of similar elements.
These similar elements could be all integers or all floats or all characters.
Usually, an array of characters is called a “string”.
An array of integers or floats is called simply an array.
All elements of any given array must be of the same type.
Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.

Arrays must be declared before they can be used.
Example:
int myArray [5] = {1,2,3,4,5};
In C Language one can have arrays of any dimensions.
Typical two-dimensional array:
int ourArray [4] [2];

To define a pointer variable, do so by preceding its name with an asterisk.
Example:
int *ptr;
ptr is the name of the variable
The int means that we intend to use the pointer variable to store the address of an integer.

Objectives

Objective 1

Learn to write programs using object-oriented problem solving concepts.

Method

Writing a program in C, using structured and object-oriented problem solving concepts, and the use of standard libraries.

Measurement

Follow your method and obtain a measurement. Document the results here.

Analysis

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

  • How did you do?
  • Room for improvement?
  • Could the measurement process be enhanced to be more effective?
  • Do you think this enhancement would be efficient to employ?
  • Could the course objective be altered to be more applicable? How would you alter it?

Experiments

Experiment 1

Question

In the DATA TYPE EXPLORATION program to determine the values for “signed char” and “unsigned char”,
I want to see what the header “#include <math.h>” line does.
Also, what will happen if I don't include it in the program.

Resources

http://www.delorie.com/gnu/docs/glibc/libc_10.html
http://www.java2s.com/Code/C/Math/Howtousepow.htm
The resources listed have a definitions of how to use header files in C programming.

Hypothesis

I don't believe the program will compile or function properly without the GNU C library header.
I believe that #include and the math.h file must be used.

Experiment

I will try to compile and run the program without the header and see what happens.
I will take the range.c program and rename it range2.c without the header and try and see if it works.

Data

Without the header the program will not compile, see below:
lab46:~/src/cprog$ gcc -o range2 range2.c -lm
range2.c: In function 'main':
range2.c:23: warning: incompatible implicit declaration of built-in function 'pow'
lab46:~/src/cprog$

BUT !!! the program will run OK…See below:

lab46:~/src/cprog$ ./range2
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values

A signed char is 1 bytes
The range of a signed char is -128 to 127
A signed char can store 256 unique values

lab46:~/src/cprog$

Analysis

Based on the data collected:

  • My hypothesis was partially correct.
  • The program would not compile, but it did run without the header.
  • At this point I am not sure if a header is absolutely necessary for a C program to function.

Conclusions

Since this program ran without the header, I will have to run other programs without headers and compare the results.

Experiment 2

Question

I will try and find out what pow() is in the DATA TYPE EXPLORATION program and find out why am I multiplying by 8.

Resources

http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.7.html#pow
http://www.codecogs.com/reference/c/math.h/pow.php
http://www.java2s.com/Code/C/Math/Howtousepow.htm
The pow() function returns base raised to the exp power.
There's a domain error if base is zero and exp is less than or equal to zero.

Hypothesis

Based on my last experiment, I don't believe the program will compile properly without the header #include <math.h>.
I believe that pow(2, (sizeof(sc)*8) must be used to get the proper value.
I will determine exactly what this math function does and how it operates, and why it needs to be multiplied by 8.

Experiment

I will change the value of 'pow' and the 'sizeof' and see what happens.
I will take the range.c program and rename it range3.c and range4.c and see what the results are.

Data

When using pow(4)and sizeof *8, here are the results:

lab46:~/src/cprog$ gcc -o range3 range3.c -lm
lab46:~/src/cprog$ ./range3
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values

A signed char is 1 bytes
The range of a signed char is 0 to -1
A signed char can store 65536 unique values
lab46:~/src/cprog$

As you can see the range of the signed char value has changed. The amount it can store has changed.
Originally the range was -128 to 127. The amount it can store was 256 unique values.

When using pow(2) and sizeof *6, here are the results:

lab46:~/src/cprog$ gcc -o range4 range4.c -lm
lab46:~/src/cprog$ ./range4
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values

A signed char is 1 bytes
The range of a signed char is -32 to 31
A signed char can store 64 unique values

lab46:~/src/cprog$

As you can see the range of the signed char value has changed. The amount it can store has changed.
Originally the range was -128 to 127. The amount it can store was 256 unique values.

Analysis

Based on the data collected:

  • My hypothesis was correct.
  • The range and unique values has changed when the pow or sizeof was changed.
  • The pow(2) and the sizeof(sc)*8 must be used to get the correct values.

Conclusions

Since a signed char is 1 byte, 2^8 will give the correct 256 unique values a char can store.

Experiment 3

Question

I am wondering what the “\n\n” is doing at the end of each stanza's printf()in the DATA TYPE EXPLORATION program.

Resources

Hypothesis

I know that \n calls for a new line. I believe that \n\n may call for 2 new lines.

Experiment

I will take the range.c program and rename it range5.c without one of the \n's at the end of the printf() stanza.
I'll try more than 2 \n's at the end of the printf() stanza and see what happens in range6.c

Data

With one \n you get the following:

lab46:~/src/cprog$ nano range5.c
lab46:~/src/cprog$ gcc -o range5 range5.c -lm
lab46:~/src/cprog$ ./range5
An unsigned char is 1 bytes
The range of an unsigned char is 0 to 255
An unsigned char can store 256 unique values
A signed char is 1 bytes
The range of a signed char is -128 to 127
A signed char can store 256 unique values
lab46:~/src/cprog$

With 3 \n\n\n you get the following

lab46:~/src/cprog$ -o range6 range6.c -lm -bash: -o: command not found lab46:~/src/cprog$ gcc -o range6 range6.c -lm lab46:~/src/cprog$ ./range6 An unsigned char is 1 bytes The range of an unsigned char is 0 to 255 An unsigned char can store 256 unique values

A signed char is 1 bytes The range of a signed char is -128 to 127 A signed char can store 256 unique values

lab46:~/src/cprog$

Analysis

Based on the data collected:

  • My hypothesis was correct.
  • One \n gives a single newline. Two \n's gives a double newlines. Three \n's gives three newlines.
  • This is what I originally thought.
  • There may be an easier way to do this. I will have to investigate.

Conclusions

To get a newline you use the \n at the end of the stanza.
I am not sure if there is a more efficient way to make more newlines. I will explore other methods.

opus/fall2011/rrichar8/part1.txt · Last modified: 2011/10/09 12:12 by rrichar8