Part 1
Part 1
Wayne Goddard
School of Computing, Clemson University, 2008
Getting Started
1.2 Goals
The goal of the course is for you to:
Though it is not the focus of the course, you should somewhat bear in mind the goals
of good programming. These include clarity and efficiency. For this course, a good
program:
• is self-describing
• is flexible
A1
//This simple program displays "hello world" to the command line.
#include <stdio.h>
The syntax of the language gives the rules for the format of statements—what goes
where. Common syntax errors include missing semi-colons, missing quotation marks
and incorrect brackets/curly braces.
The line starting with // is a comment, and is ignored by the compiler.
A string is a sequence of characters. There are a few dozen keywords (or reserved
words) such as int, main and return which are in-built in the language. The word printf
is a function call that is added by including the file stdio.h.
gcc myprog.c
which will print all warning messages. (It will help later in the course.) Then to run
the code you use
./a.out
The compiler produces the executable file a.out. The ./ part tells the operating system
to look in the current directory. (Why it doesn’t automatically is another story.)
Be aware that there are variations of C. However you develop your code, it must
run on the CS system using the above process.
A2
1.5 Rules of C
Brian Brown’s summary:
http://gd.tuwien.ac.at/languages/c/programming-bbrown/cstart.htm
A3
CpSc111 – Goddard – Notes Chapter 2
Some Basics
We look at variables, assignments and input/output.
2.2 Variables
Values are stored in memory via variables. Variables are declared before use:
int score;
int fred;
This code does two things for each variable:
• it reserves memory for the variable, which will store a whole number; and
• it tells the compiler that any other use of the word fred refers to this variable.
Once a variable has been declared, it can be assigned a value:
score=2;
fred=score;
Variables can be initialized at declaration. For example:
int count = 0;
Note that C does NOT automatically initialize variables; until you assign them a value,
they can have any value (whatever was left in memory last time that cell of memory
was used).
There are rules about what can be used as a variable name. Most of the time one
just uses lower-case letters, with a sprinkling of numbers, upper-case letters and the
underscore character . Note that reserved words such as int that have a specific
meaning cannot be used as variable names.
A4
2.3 Arithmetic Operators
For doing calculations with numbers there are many operators. The first four are the
standard arithmetic operators:
Note that the division of integers always produces another integer—what elementary-
school kids call the quotient. For example, the following code will cause x to have the
value 7:
x = 22/3;
For example, the following code will cause x to have the value 2:
x = ( 2 * ( 3 + 5 ) ) % 7 ;
The modulus operator is useful for getting values to wrap around. For example, if we
had a variable storing the hour on a 24-hour clock, it might be changed by:
hour = (hour + 1) % 24 ;
If the hour is less than 23, this justs increments it by 1; but if hour is 23, this resets it
to 0.
There are rules for operator precedence: which operator is executed before which.
Most of the time these rules behave just as one would expect. For example, multipli-
cation has precedence over addition.
The format string contains both normal characters and special codes. These codes
start with % or \. For example, a %d in the format string stands for a number (d for
decimal), and a \n means to advance the cursor to the start of the next line. The data
can be in the form of actual values or variables.
A5
will produce the output
For example, the following reads the value of number from the user:
int number;
scanf("%d", &number)
The ampersand tells the compiler to use the address in memory of the variable (to be
discussed later). If you leave this out, the code will compile but you will very probably
get the famous “Segmentation fault” error. Note that if you omit the ampersand but
are compiling with warnings enabled, gcc will warn that “format argument is not a
pointer”.
/* adder.c
* This simple program adds two user-supplied numbers
* wdg 2008
*/
#include <stdio.h>
//Main function
int main(void) {
int num1, num2, sum;
printf("Input first number: ");
scanf("%d", &num1);
printf("Input second number: ");
A6
scanf("%d", &num2);
sum = num1+num2;
printf("The sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
A7
CpSc111 – Goddard – Notes Chapter 3
A Worked Example
Consider the problem of making change with US coins for a specific amount. The
goal is a C program to do this. But first we introduce constants.
3.1 Constants
If you have the same fixed value recurring throughout the program, you should use a
constant at the top of the program. The “new” C style is to use the reserved word
const:
For the rest of the program, NUM STATES is just a normal variable, except that its
value cannot be changed. It is common style to use uppercase for constants.
In this case, the key question is what recipe (what computer science calls an algo-
rithm) should be used for making change. But cashiers know: take as many quarters
as are at most the amount; then as many dimes so that still at most the amount; and
so on.
Suppose input is stored in amount, an int variable. Then the number of quarters is
amount / 25
A8
amount % 25
return 0;
Note that the call to printf is spread over two lines; most white space is just there
for the human reader and is ignored by the compiler. Strings are an exception: they
cannot be broken over a line.
A9
CpSc111 – Goddard – Notes Chapter 4
Floating-Point Numbers
We explore the use of real numbers in C.
A10
printf("The class average is %.1f\n", 85.47);
Practice. Write code to read 5 float values from the user, and calculate their average.
For example, if the data is 11.2, 22.3, 33.4, 44.5 and 0.0, then the answer is 22.28.
4.3 Mathematics
If you #include the math.h file, then you have access to mathematical functions such
as sqrt. But note that you have to get gcc to load the math library:
/* goldBall.c */
#include <stdio.h>
#include <math.h>
int main(void) {
const float PI = acos(0.0); // or you could hardcode 3.14159 etc
const float DENSITY = 19.3; // grams per cubic cm
float diameter, radius, volume, surfaceArea, mass;
volume = 4 * PI * radius*radius*radius /3 ;
surfaceArea = 4 * PI * radius*radius ;
mass = volume * DENSITY;
A11
return 0;
}
int main(void) {
// declarations
float dollars, rands, exchangeRate;
// input
printf("Enter dollar amount ");
scanf("%f", &dollars);
printf("Enter rands per dollar ");
scanf("%f", &exchangeRate);
// processing
rands = dollars * exchangeRate;
//output
printf("%.2f dollars is %.2f rands\n", dollars, rands);
return 0;
A12
CpSc111 – Goddard – Notes Chapter 5
Reading characters is trickier because of issues with the operating system and in-
visible characters. One possibility is simply
++ is increment; -- is decrement
For the time being, we will use them only as simple single statements. The following
code will cause counter to have the value 6:
A13
int counter = 4;
counter++;
counter++;
The increment and decrement operators are usually used with int variables, but they
work with char variables too.
There are also short-cut operators. One can easily survive without them, but they
can enhance the readability. They are used when the variable on the left is the first
argument on the right. For example, the above code with counter could be written as
counter = counter + 2. But one might write is as:
counter += 2;
int pos;
printf("Enter position in alphabet: ");
scanf("%d", &pos);
upper++;
lower++;
printf("Next comes %c in upper and %c in lower\n", upper, lower );
return 0;
}
A14