Spring 2000 COMP 122 Peter Smith



Spring 2002 COMP 122 Peter Smith

Handout #7

C – Part 1

Introduction

The purpose of this handout describing the C language is to introduce you to its syntax and features. C is particularly suitable for some of the low-level operations that used to be done in assembly language. The goal is to give you a reading knowledge of the C language, i.e., you should be able to look at a C program and figure out what it does. Knowledge of C is a prerequisite for the Comp 322/L class.

You can examine the simulator for the SP machine that was written in C. We will cover the features of C used in that program. We will use C as our high-level example language when later in Comp 122 we illustrate the relationship between high-level and low-level languages. The course home page contains links to source files for the examples in this handout.

I have found the following book to be a good introduction to C.

A book on C: programming in C

Al Kelley and Ira Pohl

Addison-Wesley (4th edition, 1998)

There is good on-line help at



Example 1

Here is a simple "hello world" C program.

#include

main()

{

printf("hello world\n");

}

Notes on Example 1

1. The #include line is a directive to the pre-processor to include the contents of system file stdio.h at this point. The file contains information needed to enable us to use the printf output function.

2. The main program is always a function (subprogram) called main.

3. C uses braces {} to group statements much as some other languages use begin ... end.

4. The printf function prints the string we give it. It is actually much more general than this.

5. The \n notation in the string represents the newline character.

Assume that the source program is stored in file hello.c on the CSUN Unix system (the compiler expects files containing C source code to have the .c extension). To compile our file we give the following command:

cc -o hello hello.c

The program has no syntax errors so our compilation results in an object program called hello.. We run our object file by giving the command

hello

The output is

hello world

If we omit the -o hello parameter then we get an object file with the default name of a.out.

Example 2

The second program introduces variables and shows some input/output.

#include

/* reads two integers and outputs their average */

main()

{

int one, two;

float average;

printf("Input two integers: ");

scanf("%d %d",&one,&two);

average = ( (float)one + (float)two ) / 2.0;

printf("The average of %d and %d is %6.1f\n",one,two,average);

}

Notes on Example 2

1. text between /* and */ is commentary

2. int (integer) and float (reals) are built-in types.

3. scanf is an input routine. The first parameter describes the format of the input; the %d designates a decimal integer. Other parameters are addresses (note the &) of variables that the data is read into.

4. The notation () is a cast. It forces the following expression into the particular type.

Here we use (float) to get real equivalents of the input integers so we get a correct average.

5. In the second call of printf, note how the first parameter can be a mixture of text and format

specifications. Values in the remaining parameters are output in the corresponding formats. The

format %6.1f indicates that we would like the value of the average output as a float with a total

of 6 characters and one decimal place.

Typical output

Input two integers: 19 102

The average of 19 and 102 is 60.5

Conditionals

Example 3

Here is a program that inputs a year and determines whether or not it is a leap year.

#include

/* determine whether input year is a leap year */

main()

{

int year;

printf("Input year: ");

scanf("%d",&year);

if (year%4 != 0)

printf("%d is not a leap year",year); /* e.g. 1963 */

else if (year%100 != 0)

printf("%d is a leap year",year); /* e.g. 1984 */

else if (year%400 != 0)

printf("%d is not a leap year",year); /* e.g. 1900 */

else printf("%d is a leap year",year); /* e.g. 2000 */

}

Notes on Example 3

1. The % operator yields the remainder when the left operand is divided by the right.

2. The condition tested by the if statement is always enclosed in parentheses.

3. If we wished to have multiple statements in either branch of the if statements we would group

them with parentheses, thus:

if (condition) { s1; s2; s3; } else { s4; s5; }

4. The relational operators are: < = > != (not equals) and == (equals). If you use = instead of == the compiler will probably not complain! For example, suppose we wished to branch according to whether variable d contains 5 but instead write the following:

if (d=5) A; else B;

the effect is to assign 5 to d. The numeric value of the assignment (5) is interpreted as true (zero is false, non-zero is true) so regardless of the current value of d, action A is performed!

Example 4

Many languages have a facility for performing multi-way branches, a "case" statement of some form. [It is useful in implementing menu driven programs.] The C switch statement is illustrated in the next example.

/* illustrate use of switch statement */

main()

{

char inchar;

printf("please enter a character:");

scanf("%c",&inchar);

switch(inchar)

{

case 'w': printf("you entered lower case w");

break;

case 'm':

case 'M': printf("that was an M or m");

break;

case 'Z': printf("that was upper case Z");

break;

default : printf("I'm not sure what that was");

}

}

Notes on Example 4

1. The field designator for character input is %c.

2. In executing the switch statement, the value of the expression in parentheses is compared with the constants in the various cases to determine the action to take.

3. The break statements transfer control to the end of the switch statement. If they were omitted control would fall from one case into the next case.

4. We can have multiple constants associated with a particular action.

5. The default case is performed if none of the others matches.

Loops

C has three looping statements: while, for and do..while. Two of them are illustrated in the following example where the program prompts for an integer and outputs that number of asterisks. Input of -1 terminates the program.

Example 5

#include

main()

{

int i,count;

printf("Input count (-1 to terminate): ");

scanf("%d",&count);

while (count != -1)

{

for (i = 0; i < count; i++)

printf("*");

printf("\n");

printf("Input count (-1 to terminate): ");

scanf("%d",&count);

}

}

Notes on Example 5

1. The while statement tests the condition at the beginning of the loop. Braces are necessary when the loop body has more than one statement.

2. There are three clauses in the control part of the for statement: initialization, test and end-of-loop action.

for (A; B; C;) action ;

is equivalent to

A;

while (B) { action; C; }

Here is typical output from a run of Example 5

Input count (-1 to terminate): 12

************

Input count (-1 to terminate): 1

*

Input count (-1 to terminate): 0

Input count (-1 to terminate): 6

******

Input count (-1 to terminate): -1

Functions

All subprograms in C are called functions. They are all declared at the same level (i.e., no nesting); we have seen that the main program is a function called main.

A function should be declared before it is used but the function prototype mechanism (see below) is a convenient way not to have to worry about this. Recursion is allowed.

Example 6

A simple function that print N instances of character C.

void printchars (int N, char C)

{

int i;

for (i=0; i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download