Introduction To C
Introduction To C
The History of C
1960 International Group
ALGOL
Martin Richards.
BPCL 1967
No types
#include <stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
Programming In C 2
3.1. Compilation in 3
Stages
Stage 1: Preprocessing
Performed by a program called the preprocessor
Modifies the source code (in RAM) according to
preprocessor directives (preprocessor commands)
embedded in the source code
Strips comments and white space from the code
The source code as stored on disk is not modified.
continued 3
Stage 2: Compilation
o Performed by a program called the
compiler
o Translates the preprocessor-modified
source code into object code (machine
code)
o Checks for syntax errors and warnings
o Saves the object code to a disk file, if
instructed to do so (we will not do this).
o If any compiler errors are received, no object
code file will be generated.
o An object code file will be generated if only
warnings, not errors, are received.
Programming In C
continued 4
Stage 3: Linking
o Combines the program object code with other
object code to produce the executable file.
o The other object code can come from the Run-
Time Library, other libraries, or object files
that you have created.
o Saves the executable code to a disk file with
name and extension .exe.
o If any linker errors are received, no executable
file will be generated.
Programming In C
continued 5
Program Development
Editor
Source File prgm.c
Preprocessor
Compiler
Program Object Code File prgm.obj
Other Object Code Files (if any)
Linker
C libaray
Programming In C 7
A Simple C Program
/* Filename: hello.c
greeting “Hello, World!”
*/
#include <stdio.h>
int main ( void )
{
printf ( “Hello, World!\n” ) ;
return 0 ;
}
Programming In C 8
Program Comment
A comment is descriptive text used to help a reader
of the program understand its content.
All comments must begin with the characters /*
and end with the characters */
These are called comment delimiters
The program header comment always comes first.
Look at the class web page for the required contents
of our header comment.
Programming In C 9
Preprocessor Directives
Lines that begin with a # in column 1 are called
preprocessor directives (commands).
Example: the #include <stdio.h> directive
causes the preprocessor to include a copy of the
standard input/output header file stdio.h at this
point in the code.
This header file was included because it contains
information about the printf ( ) function that is
used in this program.
Programming In C 10
stdio.h
When we write our programs, there are
libraries of functions to help us so that we
do not have to write the same code over
and over.
Some of the functions are very complex
and long. Not having to write them
ourselves make it easier and faster to write
programs.
Using the functions will also make it easier
to learn to program!
Programming In C 11
int main ( void )
Every program must have a function called
main. This is where program execution begins.
main() is placed in the source code file as the
first function for readability.
The reserved word “int” indicates that main()
returns an integer value.
The parentheses following the reserved word
“main” indicate that it is a function.
The reserved word “void” means nothing is
there.
Programming In C 12
The Function Body
A left brace (curly bracket) -- { --
begins the body of every function. A
corresponding right brace -- } -- ends
the function body.
Programming In C 13
printf (“Hello, World!\n”)
;
This line is a C statement.
It is a call to the function printf ( )
with a single argument
(parameter), namely the string
“Hello, World!\n”.
Notice that this line ends with a
semicolon. All statements in C end
with a semicolon.
Programming In C 14
return 0 ;
Because function main() returns an integer value,
there must be a statement that indicates what this
value is.
The statement
return 0 ;
Programming In C 15
4. #include
#include <stdio.h>
Programming In C 16
stdio.h only contains function ‘headers’;
where is the actual code?
Programming In C 17
5. 2nd C program (add.c)
/* Addition program */
#include <stdio.h>
int main()
{
int x, y, z;
printf("Enter first integer\n");
scanf("%d", &x);
printf("Enter second integer\n");
scanf("%d", &y);
z = x + y;
printf("Sum is %d\n", z);
return 0;
}
Programming In C 18
Compile and Run
Programming In C 19
6. Memory as Many Boxes
Programming In C 20
Boxes are typed (e.g. int, float, etc).
This specifies their size and shape
Programming In C 21
7. 3rd C Program
(bigger.c)
/* Using the if statement, relational
operators and equality operators */
#include <stdio.h>
int main()
{
int a, b;
Programming In C
continued 22
if(a == b)
printf("%d is equal to %d\n", a, b);
if(a != b)
printf("%d is not equal to %d\n", a, b);
if(a < b)
printf("%d is < than %d\n", a, b);
Programming In C
continued 23
if(a > b)
printf("%d is > than %d\n", a, b);
if(a <= b)
printf("%d is <= to %d\n", a, b);
if(a >= b)
printf("%d is >= to %d\n", a, b);
return 0;
}
Programming In C 24
Compile and Run
Enter two integers, and I will tell
you the relationships they satisfy:
3 7
3 is not equal to 7
3 is < than 7
3 is <= to 7
Programming In C 25
8. A C Program ‘Skeleton’
(skeleton.c)
/* Name, student no. (E-mail addr.)
Date
Description of Code (5-10 lines)
*/
#include <stdio.h>
int main()
{
/* declare some variables */
/* do something */
return 0;
}
Programming In C 26
C Reserved Words
auto float sizeof
break for static
case goto struct
char if switch
const int typedef
continue
long union
default
do
register unsigned
double
return void
else short volatile
enum signed while
extern
Programming In C 27
C Data Types
int standard integer (16 bits / 2 bytes)
short short integer (8 bits / 1 byte) 1
long long integer (32 bits / 4 bytes) 1
unsigned unsigned integer
char character (8 bits / 1 byte)
float real number 1
double double precision real 1
Programming In C 28
Set of values and operation defined on
them
C supports several different types of data
Programming In C 29
Tokens
The smallest element in the C
language is the token.
It may be a single character or a
sequence of characters to form a
single item.
Programming In C 30
Tokens are:
Tokens can be:
Numeric constants
Character constants
String constants
Keywords
Names (identifiers)
Punctuation
Operators
Programming In C 31
Numeric Constants
Numeric constants are an
uninterrupted sequence of digits
(and may contain a period). They
never contain a comma.
Examples:
123
98.6
1000000
Programming In C 32
Character Constants
Singular!
One character defined character set.
Surrounded on the single quotation
mark.
Examples:
‘A’
‘a’
‘$’
‘4’
Programming In C 33
String Constants
A sequence characters surrounded by double
quotation marks.
Considered a single item.
Examples:
“UMBC”
“I like ice cream.”
“123”
“CAR”
“car”
Programming In C 34
Keywords
Sometimes called reserved words.
Are defined as a part of the C
language.
Can not be used for anything else!
Examples:
int
while
for
Programming In C 35
Names
Sometimes called identifiers.
Can be of anything length, but on the first 31 are
significant (too long is as bad as too short).
Are case sensitive:
abc is different from ABC
Must begin with a letter and the rest can be
letters, digits, and underscores.
Must follow the standards for this course!
Programming In C 36
Punctuation
Semicolons, colons, commas,
apostrophes, quotation marks,
braces, brackets, and parentheses.
; : , ‘ “ [ ] { } ( )
Programming In C 37
Naming variables
When a variable is declared it is given a name
Good programming practices
Choose a name that reflects the role of the variable in a
program, e.g.
Good: customer_name, ss_number;
Bad : cn, ss;
Don’t be afraid to have long names if it aids in readability
Restrictions
Name must begin with a letter; otherwise, can contain
digits or any other characters. C is CASE SENSITIVE! Use
31 or fewer characters to aid in portability
Programming In C 38
Variable Declaration
All variables must be declared in a C
program before the first executable
statement! Examples:
main(){
int a, b, c;
float d;
/* Do something here */
}
Programming In C 39
C Variable Names
Variable names in C may only consist of
letters, digits, and underscores and
may not begin with a digit
Variable names in C are case sensitive
ANSI standard requires only 31 or fewer
characters. Enhances portability to
follow this rule
Should be very descriptive
Programming In C 40
Variable assignment
After variables are declared, they
must (should) be given values. This is
called assignment and it is done
with the ‘=‘ operator. Examples:
float a, b;
int c;
b = 2.12;
c = 200;
Programming In C 41
char variable type
Represents a single byte (8 bits) of storage
Can be signed or unsigned
Internally char is just a number
Numerical value is associated with
character via a character set.
ASCII character set used in ANSI C
Question: what is the difference between:
printf(“%c”, someChar);
printf(“%d”, someChar);
Programming In C 42
int variable type
Represents a signed integer of typically
4 or 8 bytes (32 or 64 bits)
Precise size is machine-dependent
Question: What are the maximum and
minimum sizes of the following:
32-bit unsigned int
32-bit signed int
64-bit signed/unsigned int
Programming In C 45
Declaring variables
All variables must always be declared before the
first executable instruction in a C program
Variable declarations are always:
var_type var_name;
int age;
float annual_salary;
double weight, height; /* multiple vars ok */
In most cases, variables have no meaningful value
at this stage. Memory is set aside for them, but
they are not meaningful until assigned.
Programming In C 46
Assigning values to
Variables
Either when they are declared, or at any
subsequent time, variables are assigned values
using the “=“ operator.
Examples
int age = 52; //joint declaration/assignment
double salary;
salary = 150000.23;
age = 53; //value may change at any time
Programming In C 47
Variables in
Programming
Represent storage units in a program
Used to store/retrieve data over life of
program
Type of variable determines what can be
placed in the storage unit
Assignment – process of placing a particular
value in a variable
Variables must be declared before they are
assigned
The value of a variable can change; A
constant always has the same value
Programming In C 48
Assignment, cont.
Be careful to assign proper type – contract
between declaration and assignments
must be honored
int x=2.13 /* what is the value of x? */
double x = 3; /* is this ok? */
char c = 300; /* 300 > 1 byte; what happens?
*/
General advice
Don’t obsess too much over this at beginning
Keep it simple, stick to basic data types
We will be more pedantic later in the course
Programming In C 49
The printf Executable
Statement
The only executable statements we’ve
seen to this point are
Assignments
The printf and scanf functions
Assignment expressions with simple
operators (+, -)
Very hard to write any program without
being able to print output. Must look at
printf in more detail to start writing
useful code.
Programming In C 50
printf(), cont.
Sends output to standard out, which for now we
can think of as the terminal screen.
General form
printf(format descriptor, var1, var2, …);
format descriptor is composed of
Ordinary characters
copied directly to output
Conversion specification
Causes conversion and printing of next argument to printf
Each conversion specification begins with %
Programming In C 51
Printf() examples
Easiest to start with some examples
printf(“%s\n”, “hello world”);
Translated: “print hello world as a string followed by
a newline character”
printf(“%d\t%d\n”, j, k);
Translated: “print the value of the variable j as an
integer followed by a tab followed by the value of the
variable k as an integer followed by a new line.”
printf(“%f : %f : %f\n”, x, y, z);
English: “print the value of the floating point variable
x, followed by a space, then a colon, then a space,
etc.
Programming In C 52
More on format
statements
The format specifier in its simplest form is one
of:
%s
sequence of characters known as a String
Not a fundamental datatype in C (really an array of char)
%d
Decimal integer (ie base ten)
%f
Floating point
Note that there are many other options. These
are the most common, though, and are more
than enough to get started.
Programming In C 53
Invisible characters
Some special characters are not visible
directly in the output stream. These all
begin with an escape character (ie \);
\n newline
\t horizontal tab
\a alert bell
\v vertical tab
See K&R p.38 for more details
Programming In C 54
Arithmetic Operations
Five simple binary arithmetic operators
1. + “plus” c = a + b
2. - “minus” c = a - b
3. * “times” c = a * b
4. / “divided by” c = a/b
5. % “modulus” c = a % b
1. What are the values of c in each case
above if
int a = 10, b = 2;
float a = 10, b = 2;
int a = 10; float b = 2; ??
Programming In C 55
Relational Operators
Four basic operators for comparison of values
in C. These are typically called relational
operators:
1. > “greater than”
2. < “less than”
3. >= “greater than or equal to”
4. <= “less than or equal to”
1. For the declaration
int a=1,b=2,c;
what is the value of the following expressions?
a > b; a<b; a>=b;a<=b
Programming In C 56
Relational Operators,
cont.
Typically used with conditional expressions, e.g.
if (a < 1) then …
However, also completely valid expressions which
evaluate to a result – either 1 (true) or 0 (false).
int c, a=2, b=1;
c = (a > b)
What is the value of c?
Note: We’ll talk about order of precedence for
multipart expressions a little later. For now, we
force an order using parentheses.
Programming In C 57
Equality Operators
C distinguished between relational and
equality operators.
This is mainly to clarify rules of order of
precedence.
Two equality operators
1. == “is equal to”
2. != “is not equal to”
These follow all of the same rules for
relational operators described on the
previous slide.
Programming In C 58
Logical Operators
Logical Operators are used to create
compound expressions
There are two logical operators in C
1. || “logical or”
♦ A compound expression formed with || evaluates to 1
(true) if any one of its components is true
1. && “logical and”
♦ A compound expression formed with && evaluates to
true if all of its components are true
Programming In C
continued 59
Logical operators, like relational
operators, are typically used in
conditional expressions
1. if ( (a == 1) && (b < 3) || (c == 1) ) etc.
However, these can also be used in
regular expressions
int a = 1, b = 2, c = 3, d;
d = ( a > b ) || ( c == (b – 1) );
What is the value of d here?
Programming In C
continued 60
Logical Operators
expression1 expression2 expression1 && expression2
0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1
Fig. 4.13 Truth table for the && (logical AND) operator.
expression ! expression
0 1
nonzero 0
Fig. 4.15 Truth table for operator ! (logical negation).
Programming In C
continued 61
Logical Operators
Operators Associativity Type
++ -- + - ! ( type) right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
, left to right comma
Fig. 4.16 Operator precedence and associativity.
Programming In C 62
Bit wise logical operators
& bit wise AND
| bit wise inclusive OR
^ bit wise exclusive OR
<< left shift
>> right shift
~ one’s complement
Programming In C 63
Confusing Equality (==)
and Assignment (=)
Operators
Dangerous error
Does not ordinarily cause syntax errors
Any expression that produces a value can be
used in control structures
Nonzero values are true, zero values are false
Programming In C
continued 64
Example, replacing == with =:
if ( payCode = 4 )
printf( "You get a bonus!\n" );
This sets payCode to 4
4 is nonzero, so expression is true, and bonus
awarded no matter what the payCode was
Logic error, not a syntax error
Programming In C
continued 65
lvalues
Expressions that can appear on the left side of an equation
x = 4;
rvalues
Expressions that can only appear on the right side of an
equation
Constants, such as numbers
Cannot write 4 = x;
Must write x = 4;
y = x;
Programming In C 66
Structured-Programming
Summary
Selection
switch statement
(multiple selection)
T
break
F
T
. break
.
. F
.
.
.
T break
Programming In C
continued 67
Repetition
T
F T
T
F
F
Programming In C
continued 68
Structured-Programming
Summary
Structured programming
Easier than unstructured programs to understand, test,
debug and, modify programs
Rules for structured programming
Rules developed by programming community
Rules:
Programming In C
continued 69
Rule 2 - Any rectangle can be
Rule 1 - Begin with the
replaced by two rectangles in
simplest flowchart
sequence
.
.
.
Programming In C
continued 70
Rule 3 - Replace any rectangle with a control structure
Rule 3
Rule 3
Rule 3
Programming In C
continued 71
Stacke d b uilding b lo cks Nested build ing blocks
Programming In C
continued 72
Figure 4.23 An unstructured flowchart.
Programming In C
continued 73
All programs can be broken down into
3 controls
Sequence – handled automatically by
compiler
Selection – if, if…else or switch
Programming In C 74
Reading keyboard input
To be useful, program must be able to read
data from external source, e.g.
User input from keyboard
Database
File
Socket
Programming In C 75
Scanf function
In <stdio.f>, so no new #include(‘s)
Basic syntax
scanf( format-specifier, &var1, &var2, etc.);
Format-specifier is identical to printf
We do not need to understand everything here,
just enough to do some basic I/O
Examples
int a; scanf(“%d”,&a);
double x; scanf(“%f”,&x);
Blocks program until user enters input!
Programming In C 76
Another technique for
passing data from the
keyboard
main() can also be written as
main(int argc, char *argv[])
If main is written in this way, information can be
passed directly from the keyboard to the
program at the time of execution
For example, we may run a program called a.out as:
PROMPT > a.out Andrew Siegel
When a.out is run the two tokens Andrew and Siegel
are passed into the program and can be obtained by
querying argv and argc
Note: this involves some concepts that go beyond
what we have learned so far. We will understand fully
later.
Programming In C
continued 77
When this technique is used, each
token is stored as a separate
element in the array argv
The first token passed to the
program is stored in argv[1], the
second token in argv[2], etc.
argc stores the (integer) number of
tokens passed in
A simple example will clarify this
Programming In C 78
argc/argv example
int main (int argc, char* argv[]){
printf(“%s %d %s \n”, “you entered”, argc, “arguments”);
printf(“%s: %s\n”, “the zeroth arg is the program name”,
argv[0]);
printf(“%s: %s\n”, “the first argument is”, argv[1]);
printf(“%s: %s\n”, “the second argument is, argv[2]);
}
> gcc argv_example.c –o argv_example
> argv_example hello world
you entered 3 arguments
the zeroth argument is the program name: argv_example
the first argument is hello
the second argument is world
Programming In C
continued 79
Note that to do this completely generally we
would need to use a while or for loop
We will study while loops shortly
Also note that argv reads all arguments as
Strings (ie sequences of characters). So, we
cannot simply pass two number and add them,
for example. First, we would have to convert to
a numeric type.
Programming In C 80
Converting String to
integer
An important function when using
argv/argc is atoi.
atoi converts a String argument to an
integer in the following way:
int input, output;
input = atoi(argv[1]);
output = input + 1;
printf("%d\n", output);
> a.out 333
334
Programming In C 81