08 Beginner's Lesson 3: Basic Declarations & Expressions

Greetings,

In Lesson Two we went over some style considerations of writing a
program in C. There are many more, but those basics should be
enough to get started. In this lesson we will introduce simple
expressions and variable declarations. I'm hoping to avoid the
"Chapter 3 syndrome" of teaching C. As a collector of bargain
bin programming books, of which I have quite a few, I am quite
familiar with that syndrome. The authors start off nice and easy
and introduce things in an easy-to-understand manner. I'm thinking,
`maybe this time around I'll get it!', but right after Chapter 3,
the author gets bored with the easy approach, and goes into high
gear, passing me in both lanes. All of a sudden, they start
assuming that everything is understood. I'd like to avoid that,
if at all possible, because I painfully remember how it made me
feel. However, persistence has a lot going for it, and each
time I try again, I pick up a little more. Stick with it! That's
the key.

The hello.c program showed us what a basic one-function program
looks like. The basic structure looks like this:

/* header comments */
...Data declarations...
main()
{
...Executable statements...
return 0;
}

A basic two-function program might have this structure:

/* header comments */
...Function prototype...
...Data declarations...
main()
{
...Executable statements...
functionCall();
return 0;
}
/* function header comments */
functionCall()
{
...Executable statements...
return results;
}

Most computer programs do at least three things:

Input --> Process --> Output

The input may come from the user at a keyboard, from a file on disk,
or maybe from information or data that is within the program itself.

The executable statements within each function usually process that
data in some useful way (usually the purpose of the program).

The output is the result of the input and processing. Generally
speaking, it is the output that makes a program useful to the user.

In the Addendum to Lesson Two, I listed some C operators. Within
that list of 45 operators were the simple arithmetic operators that
allow us to multiply, divide, get a remainder, add, and subtract:

* / % + -

Multiply (*), divide (/), and modulus (%) have precedence over
addition (+) and subtraction (-). Precedence in this case means
that the C compiler will process multiplication, division, and
get a remainder before it will add or subtract.

Expressions are used to specify simple computations. You may need
to use parentheses in an expression to group terms. Here is a
sample program to try:

/* expressn.c -- using arithmetic operators in expressions */
#include <stdio.h>

int main(void)
{
printf("%d\n", 1 + 2 * 4);
printf("%d\n", (1 + 2) * 4);
printf("%d\n", 5 / 3);
printf("%d\n", 5 % 3);
printf("%d\n", 8 - 4 / 2);
printf("%d\n", (8 - 4) / 2);
printf("%d\n", 9 / 3 - 3);

return 0;
}

What happens if we put parentheses around the subtraction in the
last printf()? 9 / ( 3 - 3 ) Will your computer divide by zero?

In the above program, the "%d" in the printf function is a placeholder
for an integer expression. C allows us to store values in VARIABLES.
A variable is a reserved location in our computer's memory chips.
Each variable has a name, which makes it easy for humans to read.
Each variable also has a TYPE. The variable type tells C how
much space to reserve for the variable's value in the computer's
memory chips.

There are some rules in C for naming variables. A variable name
starts with a letter or an underscore (_) followed by any number
of letters, numbers, or underscores. Variable names are case
sensitive, so bob, Bob, and BOB are three different variables.
It is a better idea to use different names for varaibles than to
rely on different case. You may not use a C keyword as a variable
name. See the list of C keywords in Lesson Two: Addendum.

While it isn't a C rule, it is a good idea to name variables in a
way that indicates what value they hold. This makes a program
easier to understand.

Here are some examples of good variable names:

number1 /* first number */
number2 /* second number */
average /* average of numbers */
_result_one /* store result */

Here are some examples of bad variable names:

3rd_entry /* begins with a number */
why$not /* contains '$' character */
the end /* contains a space */
float /* reserved C keyword */

Before you can use a variable in C, it must be defined in a
declaration statement. The general form of a variable declaration:

variable_type variable_name; /* comment */

Remember to always end a statement with a semi-colon.
To declare an integer variable named `average':

int average; /* average of all grades */

Variables declared before the main() line are `global' variables
which may be accessed from any function in the program. Variables
declared after the main() line are local to the main() function.
Variable "scope" (global and local) is something that will be
covered later.

So, how do we know how much space to reserve for each variable?
Here is a small program that will use the `sizeof' operator to
show exactly how much memory is reserved for some commonly used
variable types.

/* var-size.c -- variable type and sizeof each one */
#include <stdio.h>

int main(void)
{
/* variable declarations */
int variable_1; /* an integer variable type */
float variable_2; /* a floating point variable */
double variable_3; /* a double precision variable */

/* output of sizeof each variable type */
printf("%d\n", sizeof(variable_1));
printf("%d\n", sizeof(variable_2));
printf("%d\n", sizeof(variable_3));

return 0;
}

In the above program, all the variables are `uninitialized'. They
do not yet have a specific value assigned to them. To assign a
value to a variable, put the variable on the left side, followed
by the assignment operator (=), with the value or expression to
be assigned to the variable on the right side, ended with a semi-
colon:

variable_name = expression;

Say it like this: "Variable_name GETS expression."

This may take the form of:

number1 = 3;
number2 = 9;
average = (number1 + number2) / 2;

Okay, now we need to look more closely at the printf() function.
The printf() function is part of the Standard Library. The general
form of printf() is:

(void) printf(format_section, expression1, expression2, ...);

printf() uses placeholders in the format_section to output the values
contained in the expressions that follow. You've already seen some
examples of this in the previous examples. The number and type of
the placeholders must match the number and type of expressions in
the printf() function. Here is an example:

int int1, int2, int3;
printf("%d %d %d", int1, int2, int3);

In the above case, all the variables have been declared as type int.
The value in int1 will print to the left, the value in int2 will output
in the middle, and the value in int3 will print to the right. If int1
has a value of 1, int2 has a value of 2, and int3 has a value of 3, then
the output of the above snippett would be: 1 2 3

So, what are those placeholders anyway? They are called "conversion
characters" and here is a handy table to use for them:

printf() Conversion Characters
==============================
Conversion
Character Meaning
----------------------------------------------------------------------
c Data item is displayed as single character
d Data item is displayed as a signed integer
e Data item is displayed as a floating point
value with an exponent
f Data item is displayed as a floating point
value without an exponent
g Data item is displayed as a floating point
value using either e-type or f-type conversion
depending on value, trailing zeros, trailing
decimal point will not be displayed.
i Data item is displayed as a signed integer
o Data item is displayed as an octal integer
without leading zero
s Data item is displayed as a string
u Data item is displayed as an unsigned integer
x Data item is displayed as a hexadecimal integer
without leading 0x
----------------------------------------------------------------------
A prefix may precede certain conversion characters
Prefix Meaning
----------------------------------------------------------------------
h Short data item (short int or short unsigned int)
l Long data item (long int, long unsigned int or double)
L Long data item (long double)
----------------------------------------------------------------------

Another example:

int a = 255;
short b = 1;
long c = 123456789;
unsigned d = 3;
double x = 123456789.123456;
char str[40] = "Bob";

printf("%5d %3hd %12ld %12lu %15.7le\n", a, b, c, d, x);
printf("%40s", str);

The above is more for future reference than anything else. As we go
along, the details will be made clear. printf() allows us to format
our output.

We've looked at the float variable type briefly in the above program
that used the sizeof operator to show us the space in memory that
some common variable types use. Real numbers are numbers that have
a fractional part, or a number with a decimal point, like 3.3 or -9.99.
The conversion character for a float is %f. The declaration for a
float is:

float variable_name; /* comment */

The type `char' represents a single character. The form of a character
declaration is:

char variable_name; /* comment */

Characters are enclosed in single quotes ('). 'A', 'a', and '!' are
character constants. The backslash character is know as the "escape
character". It is used to signal the compiler that a special character
follows. For example, \" can be used to put double quotes inside a
string. ' is a single quote. \n is a newline which causes the
output device to go to the beginning of the next line. Here is a
handy table of the escape characters:

Character | Name | Meaning
----------+-------------+-------------------------------------------
\b | Backspace | Move the cursor to the left one character
\f | Form Feed | Go to the top of a new page
\n | Newline | Go to the next line
\r | Return | Go to the beginning of the current line
\t | Tab | Advance to the next tab stop
' | Apostrophe | The character '
\" | Double quote| The character "
\ | Backslash | The character \
\nnn | octal code | nnn is the octal code for the character
--------------------------------------------------------------------

Characters use the printf() conversion character %c. This next
program example reverses three characters:

/* rev3char.c -- reverse three characters */
#include <stdio.h>

int main(void)
{
char char1 = 'A'; /* first character */
char char2 = 'B'; /* second character */
char char3 = 'C'; /* third character */
printf("%c%c%c reversed is %c%c%c\n,
char1, char2, char3,
char3, char2, char1);
return 0;
}

Note that I've assigned a value to the variables at the same
time I initialized them. If this is not easy for you to read,
then do each on a different line; the result is the same:

char char1;
char1 = 'A';

Okay, hopefully we are armed with enough information to do the
following exercises. Remember that we can't learn C by just
reading a lesson. We have to type the programs in, compile them,
run them, then modify them, and do it all over again. We have to
make some mistakes in order to learn this stuff. I have tried my
best to check all the programs I've put in this lesson, but I'm
human, so there may be a typo or two somewhere. All mistakes are mine.
If you find any, let me know!

Try these exercises on for size.

1. Write a program that prints your name, birthdate, and favorite
flavor of ice cream.
2. Write a program to print a block F using hashes (#) where the F
is eight characters high and six characters wide.
3. Write a program to compute the area and circumference of a circle
with a diameter of 12 feet. Area = pi * (radius squared)
Circumference = 2 * diameter. What changes have to be made so
it works for a circle that is 12.5 feet in diameter?
4. Write a program to print your NAME in big block letters 7 characters
high by 5 characters wide.

5. What happens if you make these mistakes in your programs:
a. Print a floating point number using the %d conversion.
b. Print an integer using the %f conversion.
c. Print a character using the %d conversion.

Happy Programming!
--
K