Table of Contents

CSci 322 Computer Architecture: Lecture #2
CSci 322 Computer Architecture: Lecture #2

CSci 322 Computer Architecture: Lecture #2

Overall Topic: Introduction to C

A Simple Program

#include <stdio.h>

/*
  This is a program that sums numbers from 0-9 and prints
  out all of the intermediate results as well.
*/

main() {
  int i, sum;

  sum = 0;
  for(i=0;i<10;i++) {
    sum += i;
    printf("The sum of %d to %d is %d\n", 0, i, sum);
  }

  return(0);
}

Relevant things:

    <return value> <functionName>(<argument list>) {
      <expressions>
    }

Compiling your function on a Unix system

The compiler you will want to use is the Gnu C compiler, called gcc. Let's say you put the above code in a file called foo.c (always end your C code files with the .c suffix). Then you can use the command

gcc foo.c 
To compile your file. By default, the executable will be put in the file a.out. If you want the compiler to put the executable somewhere else, you can use the -o option to indicate the file.

gcc -o foo foo.c
will put your executable in the file foo. Now, if you decide you want to use the math library (sin, cos, pow, sqrt, etc.) then you will need to link the math library in with your code. You link in libraries using the -l option, followed immediately by the mnemonic for the library. In the case of the math library, the command:

gcc -o foo foo.c -lm
will compile foo.c, link the math library with your program, and then put the result in foo.

Now let's say you want to split up your program into two parts. If you put one part in foo1.c, and another part in foo2.c you can use the command

gcc -o foo foo1.c foo2.c -lm
to compile foo1.c and foo2.c, link in the math library, and put the result in foo. You could also compile the two .c files separately using

gcc -c foo1.c
which will create the object file foo1.o, which you can then link together using gcc like this:

gcc -o foo foo1.o foo2.o -lm

Style

Variable Types

Arithmetic Operators

Function Calls

Statements and Control Flow


    if(<Boolean expression)
      <expressions>

<expressions> can be a single expression, or a code block between curly brackets. <Booleans expression> is simply an expression that evaluates to either 0 (FALSE) or not zero (TRUE). You can add on else if statements, and end with an else stat ement. For example:

    if(a < 1)
      return(-1);
    else if(a == 0)
      return(0);
    else
      return(1);


    while(<Boolean expression>)
      <expressions>

Other Important Topics