Brief Introduction To C
Brief Introduction To C
C is a structured programming language, which means that it allows you to develop programs using well-
defined control structures (you will learn about control structures in the articles to come), and provides
modularity (breaking the task into multiple sub tasks that are simple enough to understand and to
reuse).
C is often called a middle-level language because it combines the best elements of low-level or machine
language with high-level languages.
C is simple.
There are only 32 keywords so C is very easy to master. Keywords are words that have
special meaning in C language.
C programs run faster than programs written in most other languages.
C enables easy communication with computer hardware making it easy to write system
programs such as compilers and interpreters.
.
1. Operators
Operators are used to manipulate data. Operators perform calculations, check for
equality, make assignments, and manipulate variables. Of the 40 commonly used operators, only
18 are essential for this discussion.
Assignment Operators
= Assignment x = y;
Mathematical Operators
+ Addition x = x + y;
- Subtraction x = x – y;
* Multiplication x = x*y;
/ Division x = x/y;
% Modulus x = x %y
Logical Operators
&& Logical AND x = true && false;
|| Logical OR x = true || false;
& Bitwise AND x = x & 0xFF;
| Bitwise OR x = x | 0xFF;
~ Bitwise NOT x = x ~ 0xFF;
! Logical NOT false = !true;
>> Shift Bits Right x = x >> 1;
<< Shift Bits Left x = x << 2;
Equality Operators
== Equal to if( x == 10 ){…}
!= Not Equal to if( x != 10 ){…}
< Less than if( x < 10 ){…}
> Greater than if( x > 10 ){…}
<= Less than or equal to if( x <= 10) {…}
>= Greater than or equal to if( x >= 10){…}
Note: Mathematical Operators follow standard precedence. Multiplication and division will be
executed before any addition or subtraction.
Separators
There are 5 types of separators needed for this discussion.
{ } These separators are used to group together lines of code and initialize
arrays.
; This separator is used to separate lines of code.
( ) These separators are used to specify parameters and to change
mathematical operator precedence.
Example: Changing mathematical operator precedence:
5 + 7 * 2 = 19
( 5 + 7 ) * 2 = 24
[ ] These separators are used to index arrays.
“ “ These separators indicate a string.
/* */ These separators indicate a comment
2. Data Types
In C a data type defines the way the program stores information in memory. The size in
bytes a data type uses varies between every development system so be careful.
Data Type Description Size in Bytes ( most common)
void nothing 0
char character 1
int integer 2
long integer 4
float floating point 4
double floating point 8
All of these data types are signed. The most significant bit is used to indicate positive or
negative. A type modifier “unsigned” can be used to use the most significant bit.
Example:
int possible range of values -32,768 to 32,767
unsigned int possible range of values 0 to 65,535
Every variable used in a program must be declared.
Example:
int myvariable;
You can assign an initial value to an array by using the assignment operator.
Example:
int myvariable = 5;
An array is a collection of values. An array is allocated using the [] separator.
Example: Declaring an array of integers that holds five values.
int myarray[5];
If you want to assign an initial value to an array, you would use the {} separators.
Example: Filling an array with an initial value.
int myarray[5] = { -300, -400, -2, 4, 5};
If initial values of the array are given, the compiler is smart enough to figure out how many
positions are needed to hold the initial values.
Example: Alternative way to declare an array with initial values.
int myarray[] = { -300, -400, -2, 4, 5};
A string is an array of character values.
Example: Declaring a string.
char mystring[10];
To initialize a string, the assignment operator and “ “ separators are used. The compiler will also
place a NULL character (NULL = 0) at the end of the string to indicate the end of a string.
Example: Initializing a string.
char mystring[] = “Hello”;
To use a particular value or character in an array you can index the value using the [] separators.
Note: Index of an array starts at 0
Example: Indexing
myarray[2] from above is equal to –2
mystring[1] from above is equal to ‘e’
3. Functions
Functions are the building blocks of a C program. Functions are sections of code that
perform a single, well-defined service. All executable code in C is within a function. Functions
take any number of parameters and return a maximum of 1 value. A parameter is a value passed
to a function that is used to alter its operation or indicate the extent of its operations. A function
in C looks like this:
In the data type section, you might have wondered what the “void” type was used for. If a
function does not return a value or there are no parameters, the type void is used.
Example:
void PrintHello(void)
{
printf(“Hello World”); /* printf prints a string to the screen*/
return;
}
Another question you might ask is which function is executed first in a program. In C the
function named “main” is executed first.
Like variables, all function except the “main” function must be declared before it is defined.
Example: Declaring a function
void PrintHello(void);
Note: An array as a parameter has this form in the declaration:
void ArrayFunction(int SomeArray[]);
Then when calling the function, give the function the array’s name:
int MyArray[10];
ArrayFunction(MyArray);
int Multiply(int x, int y)
{
int z;
z = x * y;
return z;
}
Return Type Function Name parameter list
Function Body
Return Statement
4. If and else statements
The if statement is a conditional statement. If the condition given to the if statement is
true then a section of code is executed.
Syntax:
if(condition)
{ execute this code if condition is true
}
Example:
int absolute(int x)
{
if(x < 0)
{
x = -1 * x;
}
return x;
}
Sometimes, you want to perform an action when the condition is ture and perform a different
action when the condition is false. Then you can use the else statement.
Syntax:
if(condition)
{ execute this code if condition is true
}
else
{ execute this code if condition is false
}
It is very easy to chain a lot of if / else statements.
Syntax:
if(condition 1)
{
execute this code if condition 1 is true
}
else if(condition 2)
{
execute this code if condition 1 is false and condition 2 is true
}
else
{
execute this code if condition 1 and condition 2 are false
}
5. Loops
It has been proven that the only loop needed for programming is the while loop. While
the condition given to the while loop is true a section of code is executed.
Syntax:
while(condition)
{ execute this code while the condition is true
}
Example:
unsigned int factorial(unsigned int x)
{
unsigned int result;
while(x > 0)
{ result =
result*x;
x = x –1;
}
return result;
}
You can break out of a while loop prematurely by using the break statement.
Example:
int x = 0;
while(true)
{
if(x == 10000)
{
break;
}
x=x+1
}
In this example the condition given to the while loop is always true. Once x equals 10000 the
program will exit the while loop.
The other major loop is the for loop. It takes three parameters: the starting number the test
condition that determines when the loop stops and the increment expression.
Syntax:
for( initial; condition; adjust)
{
code to be executed while the condition is true
}
The for loop repeatedly executes a section of code while the condition is true. The statement
initial initializes the state of the loop. After the section of code is executed, the state is modified
using the statement adjust.
Example:
unsigned int factorial( unsigned x)
{
int counter;
unsigned int result = 1;
for( counter = 1; counter <= x; counter = counter + 1)
{ result =
result*x;
}
return result;
}
Part 2
1. File Types
Every C compiler adheres to certain “rules” regarding file extensions.
Extension
.c These are C source files. They usually contain only functions and pre-processor
commands with one exception. Any C source file containing the function “main” also
includes global variable declarations for variables used in the file and function
declarations for functions defined in the file.
.h Every C source file without the “main” function has a header file with the same name.
The header file includes pre-processor commands, global variable declarations for
variables used in the associated C source file, and function declarations for functions
defined in the associated C source file.
.o After the compiler “compiles” the C source file, a object file with the same name is
created. This is done primarily to save the compiler time. The compiler will only compile
files that have recently been changed.
.lib If the source file will never change then the programmer can create a library file. The
programmer can then use the functions in the library file. The “main” function is not
allowed in a library file.
.exe This is the only file extension that varies from system to system. When a user compiles a
program, a compiler creates object files from the source files then a linker links any
functions used in the object files together to create an executable file.
2. Library Functions
C development packages always contain standard libraries. In essence, standard functions
are provided to the programmer. The standard libraries we will be using include:
stdio.lib Standard Input and Output
int printf(const char *format[, argument, ...]);
• Accepts a series of arguments
• Applies to each argument a format specifier contained in the format string *format
• Outputs the formatted data to the screen.
To use this function, we have to give it the name of a character array or a string itself.
Example: Printing a string array.
char myString[] = “Hello World”;
printf(myString);
Example: Printing with a actual string.
printf(“Hello World”);
Using arguments and format specifiers, we can print a variable’s value to the screen. Format
specifiers can vary between development systems.
Format Specifiers
%d Integer signed decimal integer
%i Integer signed decimal integer
%o Integer unsigned octal integer
%u Integer unsigned decimal integer
%x Integer unsigned hexadecimal int (with a, b, c, d, e, f)
%X Integer unsigned hexadecimal int (with A, B, C, D, E, F)
%f Floating point signed value
%c Character Single character
%s String pointer Prints characters until a null-terminator
%% None Prints the % character
Example: Printing a variable’s value
int x = 5;
int y = x*x;
printf(“%d squared equals %d”,x,y);
The above example will print “5 squared equals 25” onto the screen.
To display non-graphical characters ( such as a new-line character) and separators, an escape
sequence is needed.
Escape Sequences
\n LF Newline (linefeed)
\r CR Carriage return
\t HT Tab (horizontal)
\\ \ Backslash
\' ' Single quote (apostrophe)
\" " Double quote
\? ? Question mark
int scanf(const char *format[, address, ...]);
• scans a series of input fields one character at a time
• formats each field according to a corresponding format specifier passed in the format
string.
Scanf is similar to printf. It is used to obtain user input. There must be one at least one
address argument. To get an address argument use the ‘&’ operator in front of variable names
but not in front of character arrays. (the ‘&’ operator is an “address of” operator.)
Example: Entering a number
int x;
printf(“Please input an integer:”);
scanf(“%d”,&x);
Example: Entering a string
int char buffer[80];
printf(“Please input a string”);
scanf(“%s”,buffer);
math.lib Math Libraries
There are many functions in the math library to do standard mathematical operations such
as: sin, cos, tangent, exponent, log, etc… You can look at the associated header file “math.h” to
find out the parameter list and return type for each function.
There are also non-mathematical functions in the math library. These functions are used to
convert a string into an integer or floating point value. These are not required for this discussion.
3. Pre-Processor
Pre-Processor directives are instructions for the compiler. Pre-processor directives are
prefixed by the ‘#’ character. For this discussion only 2 different pre-processor commands are
needed.
#include <filename.h> The include directive is used to link C source files, object files, and
library files together. For this discussion we will use this to link the
library files. This directive must appear before global variable
declarations and function declarations.
#define NAME VALUE The define directive is used to set definitions.
Example:
#define PI 3.14