Introduction to C

This lab will introduce you to how write and compile a simple C program involving a few loops.

In this lab, you'll mostly use the command line and the graphical editor. There is a C mode in NetBeans. You can try it if you like, but you'll probably on your own.

Simple C program

Start up an editor and cut-and-paste the following code into your buffer. Save the code in at file called introC1.c in a directory called csci/255.

#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("Hello world\n") ;
  return 0 ;
}

Notice there are some similarites with Java. There is a main routine with string arguments. There is also a printf which resembles the one Java finally got on version 5.

Compile and run

Go to the shell. Compile and execute your program, while looking at the files of your directory, by using the following commands.

[yourid@yourmach currentdir] cd ~/csci/255
[yourid@yourmach currentdir] ls -l
[yourid@yourmach currentdir] gcc -g -pedantic -Wall -Werror -o introC1 introC1.c
[yourid@yourmach currentdir] ls -l
[yourid@yourmach currentdir] ./introC1

The -g option to gcc tells the compiler to include debugging information in the executable introC1. The -pedantic -Wall -Werror options specify that the compiled code must comply strickly with the ISO C standard.

Adding loops

Add four loops to print out the following sequences of numbers.

  1. Every third integer from 0 to 99
  2. All squares from 0 to 144
  3. All powers of two from 1 to 128
  4. All integers from 0 to 100 divisible by either 3 or 7

To get you started, I'm going to give away the first one.

  int i ;
  for (i=0; i<=99; i=i+3) {
    printf("%d\n", i) ;
  }