C Reference

This page provides basic reference information on the C language.
It should be considered for reference only and not a substitute for attending class.

This page may NOT be referenced while a test is in progress.
Doing so will result in a grade of F for the test and possible suspension from the course.

  1. 6 basic data types in C
  2. Declaring variables in C
  3. Using printf()
  4. Format specifiers for use with printf() and scanf()
  5. Special printing characters for use with printf()
  6. Mathematical operators
  7. Logical (conditional) operators
  8. Loops (for, while, and do..while)
  9. Functions
  10. File Access

6 basic data types in C

    The 6 basic data types in C are:

  1. short - Integer data in the range -32768 to +32767, or 0 to +65535. Occupies 2 bytes of memory.
  2. int - Integer data in the range -2,147,483,648 to +2,147,483,647 or 0 to +4,294,967,295. Occupies 4 bytes of memory.
  3. long - Same as an int. Integer data in the range -2,147,483,648 to +2,147,483,647 or 0 to +4,294,967,295. Occupies 4 bytes of memory.
  4. float - Real (floating point) data in the range ±(10- 38 to 1038) with 7 significant digits. Occupies 4 bytes of memory.
  5. double - Real (floating point) data in the range ±(10- 308 to 10308) with 15 significant digits. Occupies 8 bytes of memory.
  6. char - Character data. A char data type can hold any one of the 256 characters in the ASCII character set. Occupies 1 byte of memory. Internally the char data type is stored as if it were a 1-byte integer. If you had two variables of the char data type you might say that you had a "pair of short shorts". Do not throw bricks at the computer. The UAH Computer Science Department is in no way responsible for the sick puns of its' part-time instructors.

Declaring variables in C

    Declare variables at the beginning of a function (like main()) just after the opening curly bracket or brace ({). Variable declarations consist of the data type followed by a name for the variable. Variable names may consist of any of the upper or lower case letters, any of the digits (0..9) or the dash (-) or underscore (_) characters. Variable names may not begin with a digit.

    Examples:

    short index;
    int counter;
    long milesToPlanet;
    float gradePtAvg;
    double results;
    char response;


Using printf()

    The printf() function is used to display text on the screen. The basic format of a call to the printf() function is printf, an opening parentheses (, a string in quotes which may contain optional format specifiers or special printing characters, and an optional list of variables whose values are to be printed in the corresponding locations of the format specifiers:

    Examples:

    printf("This just prints a string ending in a newline character.\n");
    printf("This prints 2 integer variables: %d, %d.\n", var1, var2);


Format specifiers for use with printf() and scanf()

    Format specifiers are used in the printf() function to indicate where the values stored in variables are to be printed and what the data type of the variable is. Each is preceeded by a percent sign (%) in the string portion of a printf() command. The available format specifiers are:

    %d -- print/input a signed integer variable (short or int).
    %ld -- print/input a signed integer variable (long).
    %f -- print/input a floating point variable (float).
    %lf -- print/input a floating point variable (double).
    %u -- print/input an unsigned integer variable.
    %o -- print/input an unsigned integer variable in octal (base 8) format.
    %x or X -- print/input an unsigned integer variable in hexadecimal (base 16) format.
    %E or E -- print/input a float or double in scientific (exponential notation)
    %c -- print/inputa character(char) variable
    %s -- print/input a character array (string).
    %% -- print/input the '%' character.

    Format specifiers also allow you to include additional formatting information including: (1) field width (number of spaces to print the variable in), (2) number of positions to the right of the decimal point, (3) print numeric data with signs (+ or -, remember the - will always be included for negative numbers), and (4) left or right justify the printed data in the specified field width.

    The following statements declare the variables used in the examples below:
    short count;
    long index;
    float avg;
    double result;

    printf("The count is now set at %10d", count);
    Print the short variable count in a field 10 spaces wide.
    printf("Current index is %-20ld", index);
    Print the long variable index left-adjusted in a field 20 spaces wide.
    printf("Your class avarage is %-10.3f", avg);
    Print the float variable avg left-adjusted in a field 10 spaces wide, with 3 decimal places
    printf("The result, %+-20.5f, was obtained. ", result);
    Print the double variable result left-adjusted in a field 20 spaces wide, with 5 decimal places, and include the "+" sign for positive values.

Special printing characters for use with printf()

    Special characters may be included in printf() strings. These include the following:

    \n -- newline
    \r -- carriage return
    \t -- horizontal tab
    \\ -- backslash
    \' -- single quote
    \" -- double quote

Mathematical operators

    Math operators used in C include:
    + Addition
    - Subtraction
    * Multiplication
    / Division
    % Modulus (remainder after an integer division, i.e. 5 % 2 = 1
    ++ Increment operator. Adds 1 to a variable, i.e. ++myVar or myVar++. If placed before the variable name the variable is pre-incremented (incremented before being used). If placed after the name of the variable the variable is post-incremented (incremented after being used). This operator can only be used with integer variables (short, int, long).
    -- Decrement operator. Subtracts 1 to a variable, i.e. --myVar or myVar--. If placed before the variable name the variable is pre-decremented (decremented before being used). If placed after the name of the variable the variable is post-decremented (decremented after being used). This operator can only be used with integer variables (short, int, long).

Logical operators

    Logical operators are used in C to make decisions in if statements and in loop controls:

      == Is equal to. Example: if(X == 3)
      > Is greater than. Example: if(X > 3)
      < Is less than. Example: if(X < 3)
      >= Is greater than or equal. Example: if(X >= 3)
      <= Is less than or equal. Example: if(X <= 3)
      != Is not equal. Example: if(X != 3)

Loops (for, while, and do..while)

    while loops
    Use a while loop when the number of times the loop is to be repeated depends on some condition which changes inside the loop. The basic structure of the while loop:

    while(condition)

      {
      /* list of commands */
      }

    Example:
    x = 0; /* Assume int x; has been declared */
    while(x < 10)
      {
      printf("x = %d", x); /* print the current value of x */
      x++; /* increment x */
      }

    for loops
    Use a for loop when the number of times the loop is to be repeated is known in advance. This may be a value known at the beginning of the program run or it may be stored in an integer variable. The basic structure of the for loop consists of (1) a loop counter initiation (i=0), (2) a condition which will terminate the loop when it become FALSE (i<10), and (3) an increment statement (i++) :

    for(initialization; condition; increment)

      {
      /* list of commands */
      }

    Example:
    /* Assume int i; has been declared */
    for(i = 0; i < 10; i++)
      {
      printf("i = %d", i); /* print the current value of i */
      }

    do...while loops
    Use a do...while loop in the exact same way you would a while loop. The important difference is that a do...while loop checks the loop termination condition at the end of the loop. This means that a do...while loop will always execute at lease once. The basic structure of the do...while :

    do

      {
      /* list of commands */
      }
    while(x < 10);

    Example:
    x = 0; /* Assume int x; has been declared */
    do
      {
      printf("x = %d", x); /* print the current value of x */
      x++; /* increment x */
      }
    while(x < 10);

Functions

    Function: A self-contained unit of program code designed to accomplish a particular task.

    Basic Concepts:

    1. Can be placed anywherein the source code, before or after main(), or even in separate source code files.
    2. Allows you to encapsulate program actions. If a particular action in a program is handled by a function and that function should have to be changed for some reason there is no change required in main() or any other function that needs to call the one that is changed. It still calls the function the same way.
    3. C is designed to use functions like building blocks.

    Basic Structure of Functions:
    
    	return_type FunctionName ( argument_list )
    		{
    function code
    }

    Prototypes

    A prototype is essentially the heading of a function definition, ending with a semi-colon (;), which is placed at the beginning of the source code or in a separate header file. The prototype should be placed in the code where it will be one of the first items read by the compiler. The purpose of the prototype is to allow give the compiler the function name, it's arguments and types, and it's return type so the compiler can check the syntax of any calls to the function during the compile process.

    Some examples of prototypes:
    	char func(void);
    	int func(int x, float f);
    	double func(char x[], float f);
    	void func(double d, int x, char s[]);
    

    Scope:
    Call by value: Only a copy of the value in a variable is sent into the function. The original variable is unchanged upon return from the function.

    Call by reference: A pointer to the variable is sent into the function instead of a value. The function then acceses the original variable using the pointer.

File Access

    Types of file I/O in C

    1. System - also called low level. The programmer must set up and keep track of the buffer used to transfer data, the format of the data and everything else. It is harder to do but more efficient.
    2. Standard - 4 types-each with its own functions.
      1. character--used to read and write single characters to a text file.
      2. string--used to read and write whole lines to a text file.
      3. formatted--used like printf() and scanf() to read and write data to a binary file.
      4. record--used to read and write whole data structures to a binary file.

    File Access in General

    All file operations consist of a 3-step process:

    1. Open a file
    2. Read from or write to the file
    3. Close the file

    Opening and closing a file

    	Step 1: Declare a pointer to a file:
    		FILE *fptr;
    		FILE is defined in  as are all the related file functions.
    
    	Step 2: Open the file by calling fopen(filename, mode). fopen() takes a file name, 
    			and a mode (read, write, append) as arguments.  It returns a pointer 
    			to type FILE. This pointer is used for all file I/O.
    		fptr = fopen("MyFile", "r"); /* Opens the file "MyFile" for reading */
    		fprt= fopen(filename, "w"); 	/* Opens the file whose name is stored */
    								/* in the character array filename for writing */
    
    		fopen():
    			1. Returns a pointer to type FILE.
    			2. Arguments are 2 character strings
    				a. filename - the name of the file to open as it appears 
    					in the disk directory. 
    				b. mode - a character string not a single character.  
    					This indicates how you intend to open the file.
    					1. "r" = read - file must already exist.
    					2. "w" = write - If the file exists its contents 
    						will be overwritten.  If not it will be created.
    					3. "a" = append - New data will be appended to the end 
    						of the present data in the file if the file exists, 
    						otherwise the file will be created.
    					4. "r+" = read & write - file must already exist.
    					5. "w+" = read & write - if the file exists its contents 
    						are overwritten. If not it is created.
    					6. "a+" = read & append - if file does not exist it is created.
    
    		Most programmers use just "r", "w" or "a" and do the read and write 
    		operations in separate functions each of which opens and closes the file.  
    		This is safer than leaving a file open while doing other things.
    
    		Data can be read and written in text(default) or binary mode.  If using binary 
    		mode you use:
    			"rb" = read binary
    			"wb" = write binary
    			"ab" = append binary
    

    How to open a file SAFELY

    	The most straight forward way to open a file is:
    
    	FILE *fptr;
    	fptr = fopen("myfile.txt", "r");
    
    	But, this works fine as long as the file already exists. 
    	If not you are in trouble, so a safer way of opening a file is
    	to check to see if it already exists first:
    
    	if ( (fptr=fopen("myfile.txt","r"))==NULL)
    		{
    		printf("Can't open file myfile.txt\n");
    		exit();
    		}
    
    	Use this statement in a function when you want to open the file.  This opens 
    	the file for reading, but if the file doesn't exist it handles that problem.  
    	If you are opening the file for writing you don't have this problem as the 
    	file will be created if it does not exist.
    
    	NOTE:  If you want to avoid overwriting a file that already exists you can 
    	do the check for !=NULL and if the result is true give a warning 
    	that the file already exists.
    

    Closing a file

    	fclose(fptr);
    	This is the same for any type of file I/O
    

    Reading, Writing, and Appending

    
    	String I/O - reads and writes whole strings to a file.
    
    		Functions:
    			int fputs(const char*, FILE *); - writes a string to a file
    			char *fgets(char *s, int n, FILE *); - reads a string from a file
    
    			fgets(string, 80, fptr); - reads at most n-1 characters into char array s and 
    			terminates it with a '\0'.  NOTE: The newline character '\n' is read in as part of 
    			the string and must be removed
    
    
    	Example 1: Write strings typed at the keyboard.  Terminates when a single [Return] is typed.
    
    		#include 
    		main()
    		{
    		FILE *ptr;
    		char string[81]; /* Use 80 char lines */
    		fptr = fopen("textfile.txt","w");
    		while (strlen(gets(string)) > 0)
    			{
    			fputs(string, fptr); /* write string */
    			fputs("\n", fptr);   /* write newline */
    			}
    		fclose(fptr);
    		}
    
    		Note the use of the string input function gets().
    		Note also that the '\0' is not written to the file 
    		so we put in a newline character to separate the strings.
    
    	Example 2: Read strings from file and write them to the screen.
    
    		#include 
    		main()
    		{
    		FILE *ptr;
    		char string[81]; /* Use 80 char lines */
    		if((fptr=fopen("textfile.txt","r"))==NULL)
    			{
    			printf("Can't open textfile.txt.\n");
    			exit();
    			}
    		while (fgets(string,80,fptr) != NULL)
    			{
    			string[strlen(string)-1] = '\0'; /* Remove '\n' */
    			printf("%s\n", string);
    			}
    		fclose(fptr);
    		}
    
    		Note the explicit removal of the newline character from the string
    

    Other I/O types

    	Character I/O - data is read or written one character at a time.
    
    		Functions:
    			char getc(FILE *); - reads one character from a file
    			char putc(int, FILE *); - writes one character to a file.  
    				Note the character is treated as an integer.
    
    	Example 1: Reads characters from the keyboard and writes them to a file until a 
    		carriage return is pressed.
    
    		#include 
    		main()
    		{
    		FILE *ptr;	/* pointer to FILE */
    		char ch;
    		fptr=fopen("textfile.txt","w");
    		while ( (ch=getche()) != '\r')
    			putc(ch, fptr);
    		fclose(fptr);
    		{
    
    		Notice that we aren't checking to see if the file exists.  We will create or 
    		overwrite it anyway.
    
    	Example 2: Reads characters from a file and writes them to the screen.
    
    		#include 
    		main()
    		{
    		FILE *ptr;	/* pointer to FILE */
    		char ch;
    		if( (fptr=fopen("textfile.txt","r")) == NULL)
    			{
    			printf("Can't open textfile.txt.\n");
    			exit();
    			}
    		while ( (ch=getc(fptr)) != EOF)
    			printf("%c", ch);
    		fclose(fptr);
    		{
    
    		Note: EOF = -1, this is not a character stored on the disk.  It is a flag 
    		transmitted by the operating system when it realizes it has read the last 
    		character in a file.  Since all ASCII characters have an integer value of 0-255 
    		-1 is unique and can be recognized as EOF.  This is also why ch is read 
    		by getc() as an int type not a char type.
    
    	Formatted I/O - Read/write formatted data like scanf() and printf()
    
    		Functions:
    			fprintf(ptr,"format specifier", varlist); - writes specified variables to disk
    			fscanf(ptr,"format specifier", varlist); - reads specified variables from disk
    
    			Warning:  You have to remember the order and format of the data 
    					in order to read it back out in a meaningful form.
    
    	Example 1: Reads an int, float, and string from the keyboard and writes them to 
    		disk.  Terminate with 2 dummy numbers and null string
    
    		#include 
    		main()
    		{
    		int inum;
    		float fnum;
    		char string[81];
    		FILE *fptr;
    		fptr = fopen("textfile.txt", "w');
    		do
    			{
    			printf("Type int, float, and string: ");
    			scanf("%d %f %s", &inum, &fnum, string);
    			fprintf(fptr,"%d %f %s",inum,fnum,string);
    			}
    		while (strlen(string) > 0);
    		fclose(fptr);
    		}
    
    
    	Example 2: Reads data back from textfile.txt
    
    		#include 
    		main()
    		{
    		int inum;
    		float fnum;
    		char string[81];
    		FILE *fptr;
    		if((fptr=fopen("textfile.txt","r'))==NULL);
    			}
    			printf("Can't open textfile.txt.\n");
    			exit();
    			}
    		while(fscanf (fptr,"%d %f %s", &inum, &fnum, string) != EOF)
    			printf("%d %f %s",inum,fnum,string);
    		fclose(fptr);
    		}
    
    	Record (binary) - reads and writes structures and arrays to disk.
    		Allows the reading and writing of large blocks of data at one time.
    
    		Functions:
    			fread(&object, sizeof(object), n, fptr);  Reads n blocks of size 
    				sizeof(object) into object.  Unless object is an array n=1.
    			fwrite(&object, sizeof(object), n, fptr);  Writes n objects of size 
    				sizeof(object) starting at &object.
    
    	Example 1:  Reads simple structures from keyboard and writes to disk.
    
    		#include 
    		main()
    		{   struct simple	/* Define a structure */
    			{
    			int num;
    			char ch;
    			} sim;
    		FILE *fptr;
    		fptr=fopen("strufile.bin", "wb");
    		do
    			{
    			printf("Type an int and a char.\n");
    			scanf("%d %c", &sim.num,&sim.ch);
    			fwrite(&sim, sizeof(struct simple),1,fptr);
    			printf("Add another structure to disk(y/n)?");
    			}
    		while(getche()=='y');
    		fclose(fptr);
    		}
    
    
    	Example 2: Reads simple structures from disk and prints to screen.
    
    		#include 
    		main()
    		{   struct simple	/* Define a structure */
    			{
    			int num;
    			char ch;
    			} sim;
    		FILE *fptr;
    
    		if( (fptr=fopen("strufile.bin", "rb"))==NULL)
    			{
    			printf("Can't open strufile.bin.\n");
    			exit();
    			}
    		while (fread(&sim, sizeof(struct simple),1, fptr)==1)
    			printf("%d %c\n.",sim.num,sim.ch);
    		fclose(fptr);
    		}
    
    		Note: fread() returns an integer value equal to the number of blocks read, ie. if 
    		we ask for one structure and fread() returns 0 we know we have reached 
    		the end of the file.
    
    




This Page is Under Construction
Check back later for additions.