Monday, January 24, 2011

C Programming class week 2

C by Discovery 4th edition by Foster and Foster

C By Discovery (4th Edition)

Chapter 2 – Gaining Control

  1. Expressions and Statements
    Expressions are sequences of tokens that can be evaluated to a numeric quantity.  A statement is a sequence of tokens that end with a semicolon and can be recognized by the compiler. Statements may not have values.
    Expressions in C are lvalues, an expression that has a location in memory, or rvalues, which can be evaluated by not changed.  X would be a lvalue, X + 3 would be an lvalue. 
  2. Blocks and Compound Statements
    A compound statement is a sequence of statements.  A block can contain compound statements as well as declarations. It must have opening and closing braces ( { } ).  It does not necessarily have to be a function but can reside in a function. If a variable is declared in the block, when the block is exited it does not exist.  This makes it a local variable.  The block can access any variables that are in the block that it exist in. 
    1. A word about style
      Not good programming style to
      A) use variables with the same name close together.
      B) All variables inside and outside blocks should be given different names
      C) A program is generally more readable if all declarations for a function appear together in one place.
  3. The if and if-else statements
    A conditional statement allows for a program to test a condition and then go in a certain direction depending on if it is true or false.  The if statement is one of these:

    if (expression)
    statement

    Expression will be a test to determine true or false, statement can be one line or a block.  Style says that after the test for the if, the line(s) that you would execute should be on the next line and indented slightly to show they are part of the if.  Along with the if statement the if else is used. 

    if (expression)
        statement
    else
         statement
    1. Compound if-else statement
      The if can be used as a series of tests as well.

      if (expression)
         statement
      else if (expression)
           statement2
      else if (expression)
           statement3
      ……….
      else
           last_statement

      When this is coded properly only one statement will be run. 
      It is possible to nest an if..else statement inside another one.  This should be done with braces to identify the statements that go with each other.  You are basically checking for the truth of one statement and the truth of another.
  4. Relational operators and expressions
    It is possible to test for relationships between variables.  They will either return a true or a false.  The relationship expressions in C are:
    Expression what it compares
    <= less than or equal to
    >= greater than or equal to
    == is equal to
    != is not equal to
    > greater than
    < less than

    x == 3 would return a true id x was equal to 3.
    4.1 A word of warning
    It is easy to make the mistake of assigning a variable in place of testing it. For example
       1: invar =3;



       2: if (intvar = 4)



       3:     printf("the number is 4\n);



    will print the “number is 4” because you are assigning the number not comparing it.


    4.2 Operator precedence

      Each side of the relationship will be calculated before it will be compared using the normal mathematical relationships tested before.




5. The while loop

Sometimes we may want to do a certain step several times (called  iterations). To do this we will use a while loop. 





   1: while (expression)



   2:     statement(s);




The first time it runs, the expression is evaluated.  If it is true the statements will run.  There will be some change of the value as part of the statements and then it will be tested again and process repeated.  Eventually it will test false and then drop out of the loop. 




5.1 using getchar() and putchar() in a loop.



getchar() and putchar() are special inputs for single characters.  This can be used in the while loop by using and EOF or end of file character. This will vary by operating systems but the popular ones are cntrl-d for Linux/Unix and ctrl-z for windows.  You can compare the input received to the EOF and terminate if it receives it.  The variable is of type int even though we are getting a character.




6. Logical operators and expressions




Another set if ways to test are:






























! logical not true if statement is false, false if statement is true
&& logical and true if both are true
|| logical or true if one side or both are true




They are evaluated in the order shown and in a left to right progression.




7. The for loop





   1: for (initialize_variable; test_to_perform; how_change_initial_value)



   2:     statements




 



8. Making C readable – programming style




8.1 Choice of identifiers

X, y and z may be legal choices, but having the variable describe what it does helps to make the code make sense later. Also a good idea to make constants all upper case.



8.2 Indentation

Indenting lines of codes in if/then and for loops make the code easier to understand.



8.3 Placement of braces

Two styles here. One is to place the open brace right after the test and the close brace as first character on line after it ends. The other is to put the open and close as the first characters on the first and last line of the block. 



8.4 Block structuring

Short blocks of code that do a single task are easier to read than larger ones.  It also makes larger programs easier when the get large and complex.



8.5 Use of parentheses

While the code may be right for the compiler, adding parentheses to math equations may not help the compiler but it may help the person trying to read it later (and that may be you). 



8.6 Comments

Use of comments is necessary to explain to a future person maintaining it what is going on. 



8.7 Paragraphing

It helps in reading the program if you break the parts of it that are similar in nature into manageable chunks. For example, the code that initializes variables might have a few blank lines after it and before the while loop to get input.



8.8 Whitespace

Whitespace, blank characters that add nothing to the code, can make it much easier to read.














Introduction to C


Tuesday, January 18, 2011

C Language Class week 1

Book: C by Discovery 4th Edition by Foster and Foster

Chapter 1: Getting Started

  1. What to Expect from C
    1. Language Level
      Programming languages are low, intermediate or high. C is intermediate to high, closer to what humans think. Assembler is how computer thinks (1s and 0s) and is considered a low level language.
    2. Programming environment
      A programing language can either assembly, interpret or compile. C is traditionally compiled and takes several steps. After that is done it is translated to the assembler language for that computer.
    3. Portability and Efficiency of C Code
      If a C program is written properly it is portable, meaning it can be run on other computer processors with no modifications. This comes at the expense of non-portable code like assembler being smaller and faster.
    4. Ease of maintenance
      Because C is a structure language and can use functions, these functions can be written in several files before the compile. Now if there is a major change that will affect one item of the program, the file that contains all references to it can be changed, and not the whole program. This makes maintaining the program much easier.
  2. Fundamentals - Reserved Words, Identifiers, the Character Set
    1. Reserved words
      Words that C uses that cannot be used for other purposes are reserved words.
    2. Identifiers or Names in C
      Identifiers are words that we choose to represent variables, subprograms and other elements. They are made up of letters, digits and underscores though they cannot start with a number. They are also case sensitive. Depending on the compiler there may be limitations as to how long they are. Lastly they cannot be identical to any keyword in C.
    3. The Character Set
      Because computers use different character sets, it is possible that extensive use of one set will make a program that is not portable.
    4. Format of C Programs
      C is a free from language that basically ignores white space put into a program
  3. Subprograms or Functions in C
    In C a subprogram is called a function. It consist of the following:

    type function_name(formal parameter declarations)
    {
    variable declarations;
    code;
    }

    Type is what type of value it will return. The rest is fairly self-explanatory.
    1. Calling a function
      If you write a separate routine to be called upon later, this is a function. In order to use it you must type its name in the calling routine and pass whatever parameters it might need.
  4. An Introduction to Output in C
    In C language, input and output are not part of the language but are external functions that come with the C compiler. To use the input and output in C, the line #include <stdio.h> must be included at the top of the program. For printing, the command printf("text to print\n"); will be used in the program. The \n represents a line feed to be done. There are other escape lines like that. \t is for tab, \b is for backspace, \" for double quotes in a string and \' for single quotes. \\ allows for a backslash to be done and lastly \0 is the null character. Also, any character that is supported in the computers character set can be done with the number of it. In \'0141' would be the letter a for example.
  5. Input and Output with Variables
    Variables are used to hold data while a program runs. In C these must be declared as to what type they are. Both of these are legal ways of declaring them in C

    int counter;
    int counter = 1;

    It is also legal to use the first one and then declare its value later on in the program. Several variable can be put on the same line if desired.
    1. Input with scanf()
      scanf() is used to input a variable from the input device. It uses two parameters. %d is the input, in this case decimal digits, and the variable name with a & in front of it, which tells the computer what memory location to put it in to correspond with the variable. It can return strange values if the input is not what it is expecting (characters in place of numbers).

      scanf("%d", &intcar);
  6. Arithmetic Operations

Symbol

Action

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

remainder

=

Assignment


 

1.6.1 Precedence of Arithmetic Operations
Unary, multiply/divide, add, subtract, assign. It is possible to make a compound assignment, meaning while assigning a variable you do one action on it. A += 1 would be the same as A = A + 1.


 

  1. Introduction to Functions and Structured Programming in C
    1. Designing a program
      1. Specify what the program is to do
      2. Analyze the program
      3. Design the software solution
      4. Translate design into code
      5. Test and debug the code
      6. Maintain an modify code as need arises.
    2. Preprocessor constants
      In defining variables in a program, constants can be used for values that will not change. These should be placed in such a way that it would take changing a value in one place to resolve any future need of changing the value.
    3. Function Parameters
      A function may have values passed to it. By definition, those values will take on the type of variable it is upon return. Any return statement stops execution of the program and returns to the calling routine.
    4. Function Calls
      A call of a function is done by its name and in ( ) next to it, any parameters it needs to pass.