Fundamentals of C Programming/Preliminaries

From Wikibooks, open books for an open world
Jump to: navigation, search

Preliminaries[edit]

How does a typical C Program look like?[edit]

First, a very simple example of a C program:

/* Sample C program that outputs the word "Hello" */
#include <stdio.h>
 
int main()
{
     printf("Hello\n");
     return 0;
}

The program shown in the example above is what is referred to as a program source code. The source code is made up of a combination of letters, numbers and other symbols. The source code can be created by the programmer/user using any text editor.

In the class, we will write C programs using the following format:

#include <stdio.h>
 
int main()
{
      /* ...your variable declarations... */
 
      /* ...your statements... */
 
      return 0;
}

What is a statement?[edit]

All C programs are made up of a sequence of instructions. In C, instructions are also called statements. In the English language, a statement is terminated by a period, a question mark or an exclamation point. Note that in C language, a statement is terminated by a semicolon. In the example program above, there is only one statement -- the printf() statement.

What is a function?[edit]

All statements should be written inside a user-defined function. You may think of a function as a group or sequence of statements. It is analogous to the English language wherein a paragraph is made up of a sequence of statements. The word "user-defined" means that it is the user who defined (or wrote) the description of a function. In the example program above, there is only one user-defined function -- the main() function. All C programs must have a main() function.


What is the use of { } symbols?[edit]

The symbol { is referred to as open brace or open curly bracket. Likewise, the symbol } is called close brace or close curly bracket. The curly brackets are used for grouping purposes. Think of an open curly bracket as something synonymous to begin and the close curly bracket as the symbol for end. Thus, in the example program above, the open and close curly brackets designate the beginning and the end of the main() function, respectively. Note that the curly brackets must always come in pair. A missing curly bracket is one of the most common cause of syntax errors.

As we shall see later on, the curly brackets are used to group several statements.


What is the use of /* */ symbols?[edit]

The symbols /* and */ are used to group comments inside the program. Comments are not instructions, rather they simply provide additional information (a textual description) such as what the program is doing, what are the inputs, what are the outputs, etc. Think of /* as the beginning of a comment, and the */ as the end of a comment. Just like the curly brackets, these symbols always come in pair. comments are optional and maybe placed anywhere within the program source code.

It is possible to write several lines of comments inside the /* */. For example:

/* The following is 
   an example 
   of a very simple C program */
void main()
{
     printf("Hello\n");
}


Note that comments cannot be nested, meaning you cannot put /* */ inside /* */. For example, the following is erroneous:

/*
   this is a comment
 
   /* this is one more comment - which will cause an error */
 
*/


What about the other symbols?[edit]

The meaning of the other symbols, i.e., #include <stdio.h> and void will be explained later.

Naming Conventions[edit]

What is a name? What are the naming conventions in C?[edit]

Data and instructions to manipulate data are referred to by their names. In C, there are rules and conventions to follow in giving a name to something; these are as follows:

1. Names are made up of letters and digits.

2. The first character MUST be a letter.

3. C is case-sensitive, meaning the lower-case letter 'a' is NOT the same as the uppercase letter 'A'.

4. The underscore symbol _ is considered as a letter in C. It is not recommended to be used, however, as the first character in a name.

5. At least the first 31 characters of a name are significant.

Examples:

The following are examples of valid names:

a

A

main

void

hello

salary

rate_per_hour

student_1

student_2

student_3

First_Name

ComputeGrade


The following are examples of invalid names:

1                 /* must start with a character */
 
1_ab              /* must start with a character */
 
a&                /* & symbol cannot be used in a name */
 
xyz_%             /* % symbol cannot be used in a name */
 
$money            /* must start with a character,
 
                     $ cannot be used in a name */



What is a keyword?[edit]

As a language, C has its own vocabulary -- a set of keywords. These names are reserved and cannot be used for other purposes such as in naming user-defined variable names. In the example program, the name void is a keyword.

The ANSI C language has 32 keywords (ONLY!).

Note that the name printf is actually not a C keyword and not really part of the C language. It is a standard input/output library pre-defined name. These distinctions will be explained later.

Constants, Variables, Data Types, Declarations[edit]

What is a constant?[edit]

A constant is an entity whose value does not change. A constant can either be a numeric constant or a literal constant.

Example:

Example of numeric constants:

1

500

-10000.100

3.1416

Example of literal constants:

'A'

"Hello"

"The quick brown fox jumped over the lazy dog."


Note: In C, a literal constant with only one character is referred to simply as a character. It is written such that it is enclosed in a pair of single quotes. If there is more than one character, it is called a string. A string is written enclosed in a pair of double quotes.


What is a variable?[edit]

A program is made of data and instructions to manipulate those data. Note that data have to be stored somewhere, and thus will need some memory space in the RAM.

A variable is an entity that is used to store data. Without variables, there is no way (or actually NO PLACE) to store data. A variable has

  • a name (more specifically a symbolic name)
  • an associated physical memory space (portion in a RAM)
  • a data type
  • a value (depends on data type)
  • a scope
  • a lifetime

The concept of scope and lifetime will be discussed in the latter part of the course.


What is a data type?[edit]

A data type specifies

  • the kind of values that can be assumed by a variable of that type
  • The range of values that can be assumed by a variable of that type
  • the amount of memory (in bytes) needed by a variable to store a value of that type


What (basic) data types are available in C language?[edit]

There are four basic data types, namely:

  • char - the character data type. The char data type is used to represent/store/manipulate character data values. A char data type value requires one byte of memory space. The range of values that can be assumed by a char value is from 0 to 255. The number-to-character coding that is used is ASCII.
  • int - the integer data type. The int data type is used to represent/store/manipulate signed whole numeric values.
  • float - the single precision floating point data type. The float data type is used to store single precision signed real numbers(i.e., those numbers with decimal values).
  • double - the double precision floating point data type. The double data type is used to store double precision signed real numbers(i.e., bigger numbers with decimal values).


The amount of memory space required to store an int, a float and double is platform-dependent (depends on the machine and the software). For 32-bit machines (and 32-bit compilers such as Microsoft C compiler), an int and float requires 4 bytes of memory each, while a double requires 8 bytes of memory.

Note that a char data is actually numeric (0 to 255), and is treated as a subset of int values. Any operation (discussed later) on integer values can also be performed on characters.


Assignment:

Find out what is the range of values (minimum and maximum values) for the following data types: int, float, double on your platform. Hint: Try to look for two files named "limits.h" and "float.h" that comes together with your C compiler.


How can you determine the actual size of each data type?[edit]

The following program can be used to print the sizes of the basic data types:

#include <stdio.h>
 
int main()
{
     printf("Size of char: %d\n", sizeof(char));
     printf("Size of int: %d\n", sizeof(int));
     printf("Size of float: %d\n", sizeof(float));
     printf("Size of double: %d\n", sizeof(double));
 
     return 0;
     getch();
 
}


The sizeof is a keyword in C. It is an operator that yields the size in number of bytes of the specified data type shown above.

What is variable declaration?[edit]

A variable declaration is an "action" by which a variable is "introduced" to a program/function. All variables in a C program must be declared. If you forgot to do so, the compiler will report a syntax error.


How do you declare a variable?[edit]

In C, the syntax for declaring a variable is as follows:

<variable name>


The symbol <item> means that it is required to specify the item enclosed within a pair of angled brackets. A semicolon signifies the end of a declaration. A missing semicolon will cause the compiler to generate a syntax error. Variables should be named following the C naming conventions.

Example:

char ch;

int i;

float f;

double d;


It is possible to declare several variables of the same type on the same line. In such a case, a comma should be inserted between two variables. A missing comma will generate a syntax error.

Example:

char ch1, ch2;

int x, y, z;

float hourly_rate, number_of_hours, salary;

double numerator, denominator;


Can I use any name for the variables?[edit]

Yes, as long as you follow the naming conventions, and do not use the C reserved words.

It is recommended, however, as a good programming practice for you to use a name that is descriptive or suggestive. For example, if you know that a variable will represent the hourly rate of a part-time worker, then don't use names such as xyz or x1. It is better to use a variable name such as rate or hourly_rate. Note that the use of the underscore makes the variable name easy to read.

What is the value of the variable initially?[edit]

By default, the value of a variable in C is GARBAGE, meaning there is something stored in that memory space but that something is invalid for the intended use.

A variable must be properly initialized. By initialize, we mean assigning a valid value to a variable. The use of a variable with a garbage value will cause a logical error -- another type of error that is very difficult to find.

Exercises:

1. Declare middle initial as a character variable

2. Declare age as an integer variable

3. Declare deposit amount, withdrawal amount as floating point variables

4. Declare length, width, height as double data type variables