Title: Welcome to C
1Welcome to C
- Fundamentals
- Variables and Constants
- C basic Data Types
- Assignments
- Character Arrays
- Preprocessor Directives
- Input and output
2Why C?
- C is the common denominator of many of todays
languages - Cs strong points
- very efficient
- weakly typed language
- Small structured language with many operators
- Has no input/output statements! It uses function
calls - hardware independence
- Originated at Bell Labs, Dennis Ritchie 1972
implemented - Development language for UNIX operating system
3C Standard Library
- C programs consist of functions
- Most C programmers take advantage of existing
functions in the C standard library - Learn the C language
- Learn how to use the library avoid reinventing
the wheel - Your program building blocks
- Functions you write yourself
- Library functions (enhance the portability of
your program)
4The C Programming Process
- Design your solution
- Inputs, outputs and logical steps to achieve the
outputs - Test your solution
- Code your solution
- Compile Edit your program
- Handling errors
- Run and Test your program
5Before and after Compilation
- Editor editing your source file
- Compiler routes your program first through
Preprocessor (pre-compiler) to prepare it for
compilation. The compiler produces object code - Linker the compiler sends runtime information
(such as memory addresses) or combines several
compiled programs into one executable file - Your program is loaded to memory to Execute and
test and perhaps re-edit, re-compile,
6Studying an outline
- include ltstdio.hgt
- main()
-
- Code
- goes
- here
-
- Multiple procedures and
- blocks are optional
- depending on the programs
- requirements
-
A procedure name
Preprocessor Directives go here
A block
7Studying a Program
- / First.c This is a sample program. It doesnt
do much / - include ltstdio.hgt / To use the functions in
that library / - int main() / All C programs require this line
and the braces / -
- int i, j / These 3 lines declare 4 variables
/ - char c
- float x
-
- i 4 / i and j are assigned integer values
/ - j i 7
- c A / All character constants are
enclosed in single quotes/ - x 9.087 / x requires a floating-point value
since it was declared as a floating-point
variable / - x x 4.5 / change what was in x with a
formula / - / Sends the values of the variables to the
screen / - printf(d d c f, i, j, c, x)
-
- return 0 / End programs and functions with
return /
Output 4 11 A 40.891499
8The format of a C program
- Readability is IMPORTANT
- Use white space to make programs readable
- Use Comments to explain whats going on to you
(later) and other programmers - / any mixture of characters in upper or lower
case / - // A newer way to write comments
- DO NOT nest comments
- / start comment 1 / comment 2 / finish comment
1 / - UPPERCASE and lowercase
- the entire C language is lowercase
- C programmers reserve UPPERCASE for some names
(like constants)
- include ltstdio.hgt/ To use the functions in that
library / - main() / All C programs require this line and
the braces / - int i, j / These 3 lines declare 4 variables
/ char cfloat x i 4 / i and j are assigned
integer values / - j i 7c A / All character constants
are enclosed in single quotes/ - x 9.087 / x requires a floating-point value
since it was declared as a floating-point
variable / x x 4.5 / change what was in x
with a formula // Sends the values of the
variables to the screen /printf(d d c f,
i, j, c, x)return 0 / End programs and
functions with return /
9Makeup of Programs
Always ends with a semi colon
- Data
- Variables a box in memory that hold data that
change in the program - Number
- Character
- Constants any number, character, word or
phrase a constant does not change - Character-based
- A
- May
- Number-based
- 10
- -3.4
- Commands
- Declarations char c
- Declares a character variable called c
- Assignments j i 7
- Adds 7 to the variables is value
- function calls
- printf(d d c f, i, j, c, x)
- Sends output to the screen.
- sqrt(16)
- obtains the sqrt of 16
- Other statements such as
- return 0 / exit a function /
10Data Processing with C Variables and
Constants
- Data types Cs 4 main types
- int 45 -932 0 12
- char A B C
- float 45.12 -322.22 0.00 .4356
- Double 45.0123456789
- Naming conventions
- Unique names
- Begins with a letter, then any letter, digit or
underscore ( _ ) - Meaningful names - NOT keywords, function names
or commands
- Declaring and assigning values
- Position (unless global
- after the opening brace of a block of code
(usually at the top of a function) - before a function name (such as before main() in
the program) - Attributes
- Name age salary first_name
- Type/Size int float char
- Value 20 1500.00 Name here
aggregate type
11Declaring variables - type
- char variables hold only one character
- int hold whole numbers
- float and double (double precision) hold numbers
that contain decimal points - Same precedence as in Maths
- C has many more operators
- State type and name(s), and initial values
(optional) - int i
- char a, b, c
- Assign or initialize variables using values that
have a matching type to that of the declared name - i 4
- j i 7 // j must be of type int
Primary math operators Add - Subtract Multi
ply / Divide
12Declaring variables - position
- global variables
- include ltstdio.hgt
- int num100 / declaration of global
variable FORBIDDEN !! / - int main()
-
- printf("Global value is d", num)
- //d means print a decimal value
- return 0
-
- local variables
- include ltstdio.hgt
- int main()
-
- int num10 / declaration of local variable /
- printf(Local value is d", num)
- return 0
-
Prints 10
Prints 100
13Declaring variables quantifiers
- Quantifiers such as long, short, signed and
unsigned could be applied to these basic data
types - short keyword can be used with int to indicate a
short integer (usually the range of values for
int are at least the same as for short and less
than long - long keyword can precede an int or double to
indicate that the number being stored is longer
than usual - unsigned extra storage range
- signed if your data contains negative values
less range - C does not have a string-type variable you need
an aggregate variable type that combine other
fundamental types, e.g. array (later!) - Complex data types include enumerations, arrays,
structures, unions, lists, stacks, queues, trees - Pointers are a special data type that can hold a
memory address
14C Data Types
Minimum ranges that are used follows ANSI C
standard
15Assigning Values to variables
- An assignment statement take the form
- variable expression
A name you declared earlier
Any variable, constant, expression, or
combination
produces a result that is the same data type as
the variables
main() char first, middle, last int
age float salary first A middle
B last C age 28 salary
25000.00 // Rest of the program
You can assign variables or mathematical
expressions to other variables, e.g.
payable_tax salary tax_rate Do not mix
types in assignments, e.g. middle 123.45 //
Do not do this!
Do not put commas
16L-Value R-Value
- L-values
- Expressions that can appear on left side of
equation - Can be changed (i.e., variables)
- e.g. x 4
- R-values
- Only appear on right side of equation
- Constants, such as numbers (i.e. cannot write 4
x) - L-values can be used as R-values, but NOT vice
versa
17char and int in C
- Integers and character variables can be used
interchangeably - Each ASCII character has a unique identification
number - char ch
- ch T 5 // Add 5 to the ASCII character.
- The ASCII value of T is 84.
- 84 5 89
- The value Y in c.
- int i P // Assigns the value 80 to i
18Constants
Literal constant
- include ltstdio.hgt
- main()
- const float PI 3.141593
- float diameter, radius, circ, area
- printf("\nEnter the diameter of a ")
- printf(" circle in mm ")
- scanf("f", diameter)
- circ PI diameter
- radius diameter / 2.0
- area PI (radius radius)
- printf("\tIts circumference is .2f mm\n",
circ) - printf("\tAnd its area is .2f sq.mm\n ", area)
- return 0
-
- Constants are declared using const keyword
- Symbolic Constants are defined in the
preprocessor area of the program, declared using
define CONSTANT_NAME Value
19Constants
- Literal Constants
- int base10 decimal whole number without a
decimal point, e.g. 65535 - Octal in base8 e.g. 177777
- Hexadecimal in base16 e.g. 0xFFFF
- float a number that contains a fractional
portion - char a single character enclosed in single
quotation marks, e.g. A
- String Constants
- Anything enclosed in double quotation marks,
e.g.C Programming
In memory, the length of C is 2, Hello is 6
20String Constants
- Is always enclosed in double quotation marks,
examples - C Program 123 62 Independence
Sq. x - Any group of characters, digits and punctuation.
- All string constants end with a NULL character.
You do not see the \0, but C makes sure it
stores the NULL character at the end of the
string in memory. - This is how C can tell the end of a string.
21Introducing Arrays
- Suppose you want to hold the name, age and salary
in variables - age and salary are easy because there are
variable types that can hold such data - int age
- float salary
- For name you need many character variables next
to each other in memory a character array - char name15
- An array declaration always includes brackets (
) that declare the storage C needs to reserve
for the array - This declaration reserves 15 character spaces
therefore length of name can be anything up to
14 characters (we will see why that is the case)
22Initializing Character Arrays
- Using a string literal
- char name Michael Jones
- C will count the strings length, adds one for
the null zero - This statement will reserve space for 14
characters (13 characters in addition to the Cs
string terminating symbol - Null Zero - Using individual characters
- char name M,i,c,h,a,e,l,
,J,o,n,e,s,\0 - Create an array capable of holding a specific
number of characters - char name15
- This statement will reserve 15 spaces including
the Null Zero - Names that can be stored in this array cannot
exceed 14 characters - Declare with Missing information no size and
array is not initialized! - char name /does nothing/
- C will assume that this array contains zero
elements
23Assigning values to Arrays
In memory
- Declaring the size
- char name15 Michael Jones
- This reserves 15 spaces to hold names up to 14
characters long the 15th space is the Null Zero - Each of the 15 boxes of the array is called an
element. - Notice the null zero (the string terminating
character) at the end of the string. - Notice also that the last character of the array
contains no data - You must reserve enough space for your data
- char name5 Michael Jones
- /not enough/
24Access to individual array elements
- You can access the array as a whole or single
elements of it - You can assign values to the individual array
elements by putting the elements location,
called the subscript, in brackets, as follows - name3 k / overwrites the h (at subscript
3) in the name Michael with a k / - All array subscripts start at zero - assigning
name3 changes the fourth element In the array
- You can use the subscript notation to assign
initial values to an array later in the program - name0 first char
- name1 second char
- name2 third char
-
-
- name13 last char
- name14\0 /Needed to ensure this is a
string/
25The strcpy() function
- is a built-in function in string.h standard
library like printf() in stdio.h that allows
you to copy a string constant into a string. - To copy Michael Jones into name, you would
type - strcpy(name, Michael Jones)
- first value in the parenthesis is a character
array name (must be long enough to hold the
string), and that the second value is a valid
string constant or another character array that
holds a string
26Preprocessor Directives
- commands to the preprocessor - typically placed
at column 1 at the top of your program - include ltstdio.hgt
- main()
-
- begin with a hash sign () - Never put a
semicolon at the end of the preprocessor
directives because they are pre-processor
commands and not C commands - The include preprocessor directive merges a disk
file into your source program. - include ltfilenamegt / The search for the file is
performed in an implementation-dependent
manner i.e. in pre- designated directories / - or
- include filename / The pre-processor searches
in the same directory as the file being
compiled for the file to be included /
27The include directive
- Suppose you print your name and address often in
your C programs using the following lines - printf(Akil Wamucia\n)
- printf(Apartment 2\n)
- printf(233 Atlantic Way\n)
- printf(St. Andrew\n)
- printf(Barbados\n)
- Instead of typing this every time!
- save them in a file called myadd.c. from then on,
you would only need to type the single line - include ltmyadd.cgt
- The include directive is mostly used to include
special programs called header files (using a .h
extension) that come with your C compiler - The most common header file is named stdio.h
(standard input/output header) that gives your
compiler needed information about built-in
routines that perform input and output such as
the printf().
28The define directive
- works in exactly the same way as the
search-and-replace command found in word
processors - define ARGUMENT1 ARGUMENT2
- ARGUMENT1 is a single word with no spaces
- ARGUMENT2 can be any character, word or phrase
- The define directive replaces all occurrences of
ARGUMENT1 in your program with the contents of
ARGUMENT2 before compilation - ARGUMENT1 is NOT a variable
- Saves memory
- Easy modification to programs
29Input and output
- The printf() function and its optional arguments
- basic screen output function
- Control Strings
- Conversion Specifiers
- Escape Sequence
- Modifying Conversion Characters
- The scanf() function
- basic keyboard input function
30The printf() function
- A C library function in the ltstdio.hgt library.
Sends data to the standard output device (screen)
unless you redirect the standard output to a
different device , using the format - printf(control_string , one or more values)
- The control \ format string contains
- Literal text is printed as is without variation
- printf(Your Text)
- Escaped sequences special characters preceded
by \ - printf(Text on first line\nText on second
line) - Conversion specifiers followed by a single
character - Indicates (usually) that a variable is to be
printed at this location in the output stream. - printf(c d f, a_char_var, an_integer_var,
a_float_var) - All together
- printf(character c integer d float f,
a_char_var, an_integer_var, a_float_var) - The variables to be printed must appear in the
parameters to printf following the format string,
in the order that they appear in the format
string.
optional
31Escape Sequence
32Escape Sequence
- To print two names on two different lines,
include \n between them - printf(Harry or\nJerry\?)
- This program rings a bell on your computer by
assigning the \a escape sequence to a variable
and then printing that variable - //This program rings a bell.
- include ltstdio.hgt
- main()
-
- char bell \a
- printf(c, bell) //c means print a
character value - return
Harry or Jerry?
To print a question mark at the end of the second
line
33Conversion Specifiers
- There must be one conversion specifier for each
argument being printed out! - Ensure you use the correct specifier for the type
of data you are printing!
34What would this program print?
- include ltstdio.hgt
- int main()
- int ten10,x42
- char ch1'o', ch2'f'
- printf("d cc d is f\n",ten,ch1,ch2,x,
1.0x / ten ) - return 0
Why do we need to do this? We will talk about a
better way later.
35Conversion Specifiers Modifiers
- floating-point numbers (using f) print with too
many decimal places for most applications - insert a modifying number inside to tell C how
many positions to print
prints
- many C programmers ignore the width specifier
part and specify only the decimal part as in
.2f. - Similarly, the width of strings can be
controlled. Use the width modifier in the s
string conversion character - if you do not
specify enough width to output the full string, C
ignores your width
36Keep Count of Output
- your printed values must match the control_string
supplied with them - printf("The result is d and d\n", a, b)
- A mismatched value will produce garbage with ONE
exception - printf(c, 65) // Prints letter A
- printf(d, A) // Prints the number 65
37The scanf() function
- A C library function in the ltstdio.hgt library
- one way to get input from the keyboard
- Uses a similar format as printf()
- scanf(control_string , one or more values)
- Uses same conversion specifiers EXCEPT
- never include the newline character ( \n ) with a
scanf() control_string as the function knows
that the input is finished with the user presses
Enter ? - Another problem with scanf()
- requires the use of pointer variables this will
become clear when you learn pointers - For now, Always remember to put an ampersand (
) before variable names inside a scanf() - scanf(d, anInteger) //anInteger is declared
as int
38The scanf() function
- Reading more than one variables in one time
- int n1,n2
- float f
- scanf("ddf",n1,n2,f)
- requires that your user type the input exactly
the way the control_string specifies! - You can use other characters to separate the
numbers - scanf("valued,ratiof", value,ratio)
- You must provide input like value27,ratio0.8
- You cannot control your users typing. If
incorrect data is entered there is not much you
can do apart from verifying it. - If you are reading into a long or a double, you
must precede the conversion specifier with an l
(a lower case L)
39Reading Long numbers
- int main()
- int x
- long y
- float a
- double b
- scanf("d ld f lf", x, y, a, b)
- return 0
40Printing Arrays
- You can print the entire string (or array) by
using s conversion specifier - printf(s, name) / do not put the brackets
after the array name / - you can print it with or without the (s the
string format code). - printf(name)
- You can input a string from the keyboard using
- scanf(s, name)