You are on page 1of 43

1

Introduction to C Programming

Why use C?
Mainly because it produces code that runs nearly as fast
as code written in assembly language. Some examples
of the use of C might be:

Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Data Bases
Language Interpreters
Utilities

C Programming Language
Developed by Dennis Ritchie at Bell Laboratories in 1972
based upon the B programming language.
It was then used widely in Unix systems.
The C Language spread like wild fire, over various
hardware platforms, all over the IT world, to such an
extend that variations and incompatibilities started
creeping up.
Therefore there was a need for a standard code so that any
programs written in C can be compiled by any compilers.
In 1983, the X3J11 Technical Committee came up with the
draft proposal for the ANSI system, which was approved
in 1989 and referred to as theANSI/ISO 9899 : 1990 or
simply the ANSI C, which is now the global solution.

Why C Still Useful?


C provides:

Efficiency, high performance and high quality s/ws


flexibility and power
many high-level and low-level operations middle level
Stability and small size code
Provide functionality through rich set of function libraries
Gateway for other professional languages like C C++ Java

C is used:

System software Compilers, Editors, embedded systems


data compression, graphics and computational geometry, utility
programs
databases, operating systems, device drivers, system level routines
there are zillions of lines of C legacy code
Also used in application programs

Development with C

Four stages
Editing: Writing the source code by using some IDE or editor
Preprocessing or libraries: Already available routines
compiling: translates or converts source to object code for a specific
platform source code -> object code
linking:
resolves external references and produces the executable
module

Portable programs will run on any machine but..


Note! Program correctness and robustness are most important than
program efficiency

How does it all fit together?


Output device

C Code

Compiler & Linker


Processor

Binary code

Hard drive

Software side

Hardware side

(done when we compile

(realtime)

the program)

C Standard Library
Two parts to learning the C world
Learn C itself
Take advantage of rich collection of existing functions called
C Standard Library

Avoid reinventing the wheel


SW reusability

Basics of C Environment
C systems consist of 3 parts
Environment
Language
C Standard Library

Development environment has 6 phases

Edit
Pre-processor
Compile
Link
Load
Execute

Basics of C Environment
Program edited in
Phase 1

Editor

Disk

Editor and stored


on disk
Preprocessor

Phase 2 Preprocessor

Disk

program processes
the code
Creates object code

Phase 3

Compiler

Disk

and stores on disk


Links object code

Phase 4

Linker

Disk

with libraries and


stores on disk

Basics of C Environment
Primary memory
Phase 5

Loader

memory

Primary memory
Phase 6

CPU

Puts program in

Takes each instruction


and executes it storing
new data values

Simple C Program
/* A first C Program*/
#include <stdio.h>
void main()
{
printf("Hello World \n");
}

Simple C Program
Line 1: #include <stdio.h>
As part of compilation, the C compiler runs a
program called the C preprocessor. The
preprocessor is able to add and remove code from
your source file.
In this case, the directive #include tells the
preprocessor to include code from the file stdio.h.
This file contains declarations for functions that
the program needs to use. A declaration for the
printf function is in this file.

Simple C Program
Line 2: void main()
This statement declares the main function.
A C program can contain many functions but must
always have one main function.
A function is a self-contained module of code that
can accomplish some task.
Functions are examined later.
The "void" specifies the return type of main. In
this case, nothing is returned to the operating
system.

Simple C Program
Line 3: {
This opening bracket denotes the start of the
program.

Simple C Program
Line 4: printf("Hello World From About\n");
Printf is a function from a standard C library that is
used to print strings to the standard output, normally
your screen.
The compiler links code from these standard libraries
to the code you have written to produce the final
executable.
The "\n" is a special format modifier that tells the
printf to put a line feed at the end of the line.
If there were another printf in this program, its
string would print on the next line.

Simple C Program
Line 5: }

This closing bracket denotes the end of the


program.

C Standard Header Files you may want to use


Standard Headers you should know about:
stdio.h file and console (also a file) IO: perror, printf,
open, close, read, write, scanf, etc.
stdlib.h - common utility functions: malloc, calloc,
strtol, atoi, etc
string.h - string and byte manipulation: strlen, strcpy,
strcat, memcpy, memset, etc.
ctype.h character types: isalnum, isprint,
isupport, tolower, etc.
errno.h defines errno used for reporting system errors
math.h math functions: ceil, exp, floor, sqrt, etc.
signal.h signal handling facility: raise, signal, etc
stdint.h standard integer: intN_t, uintN_t, etc
time.h time related facility: asctime, clock, time_t,
etc.

The Preprocessor
The C preprocessor permits you to define simple macros
that are evaluated and expanded prior to compilation.
Commands begin with a #. Abbreviated list:

#define : defines a macro


#undef : removes a macro definition
#include : insert text from file
#if : conditional based on value of expression
#ifdef : conditional based on whether macro defined
#ifndef : conditional based on whether macro is not defined
#else : alternative
#elif : conditional alternative
defined() : preprocessor function: 1 if name defined, else 0
#if defined(__NetBSD__)

Preprocessor: Macros
Using macros as functions, exercise caution:
flawed example: #define mymult(a,b) a*b
Source: k = mymult(i-1, j+5);
Post preprocessing: k = i 1 * j + 5;

better: #define mymult(a,b) (a)*(b)


Source: k = mymult(i-1, j+5);
Post preprocessing: k = (i 1)*(j + 5);

Be careful of side effects, for example what if we did the


following
Macro: #define mysq(a) (a)*(a)
flawed usage:
Source: k = mysq(i++)
Post preprocessing: k = (i++)*(i++)

Alternative is to use inlineed functions


inline int mysq(int a) {return a*a};
mysq(i++) works as expected in this case.

Preprocessor: Conditional Compilation


Its generally better to use inlineed functions
Typically you will use the preprocessor to define
constants, perform conditional code inclusion, include
header files or to create shortcuts
#define DEFAULT_SAMPLES 100
#ifdef __linux
static inline int64_t
gettime(void) {...}

#elif defined(sun)
static inline int64_t
gettime(void) {return (int64_t)gethrtime()}

#else
static inline int64_t
gettime(void) {... gettimeofday()...}

#endif

Escape Sequence

\n
\t
\r
\a
\\
\

new line
tab
carriage return
alert
backslash
double quote

Arithmetic in C
C operation
Addition(+)
Subtraction (-)
Multiplication(*)
Division(/)
Modulus(%)

Algebraic C
f+7
p-c
bm
x/y, x , x y
r mod s

f+7
p-c
b*m
x/y
r%s

Memory concepts
Every variable has a name, type and value
Variable names correspond to locations in
computer memory
New value over-writes the previous value
Destructive read-in
Value reading called Non-destructive read-out

2. A Simple C Program
1
2
3
4
5
6
7
8
9
10

/* Fig. 2.1: fig02_01.c


A first program in C */
#include <stdio.h>
int main()
{
printf( "Welcome to C!\n" );
return 0;
}

Comments
Text surrounded by /* and */ is ignored by computer
Used to describe useful program information (description,
author, date)

#include <stdio.h>
Preprocessor directive
Tells computer to load contents of a certain library header file

<stdio.h> allows standard input/output operations

2.

A Simple C Program

int main()
C++ programs contain one or more functions, exactly one of
which must be main
Parenthesis used to indicate a function
int means that main "returns" an integer value
Braces ({ and }) indicate a block
The bodies of all functions must be contained in braces

2.

A Simple C Program

printf( "Welcome to C!\n" );


Instructs computer to perform an action
Specifically, prints the string of characters within quotes ( )

Entire line called a statement


All statements must end with a semicolon (;)

Escape character (\)


Indicates that printf should do something out of the ordinary
\n is the newline character

2.

A Simple C Program

return 0;
A way to exit a function
return 0, in this case, means that the main() function
terminates normally and returns to the Windows operating
system.

Right brace }
Indicates end of main has been reached

Linker
When a function is called, linker locates it in the library
Inserts it into object program
If function name is misspelled, the linker will produce an
error because it will not be able to find function in the
library

Good programming practices


Indentation
#include <stdio.h>
int main() {
printf("Hello World!\n");
return 0;
}

#include <stdio.h>
int main() {
printf("Hello
World!\n");
return 0;
}

C Course, Programming club, Fall 2008

28

Good programming practices contd..


Variables names
Not too short, not too long
Always start variable names with small letters
On work break
Capitalize: myVariable, OR
Separate: my_variable

C Course, Programming club, Fall 2008

29

Good programming practices contd...


Put comments
#include <stdio.h>
int main() {
/* this program adds
two numbers */
int a = 4; //first number
int b = 5; //second number
int res = 0; //result
res = a + b;
}

C Course, Programming club, Fall 2008

30

Good programming practices

Your code may be used by somebody else


The code may be long
Should be easy to understand for you and for others
Saves lot of errors and makes debugging easier
Speeds up program development

C Course, Programming club, Fall 2008

31

3.

Another Simple C Program

1 /* Fig. 2.5: fig02_05.c


2

Addition program */

3 #include <stdio.h>
4
5 int main()
6 {
7

int integer1, integer2, sum;

/* declaration */

printf( "Enter first integer\n" );

/* prompt */

10

scanf( "%d", &integer1 );

/* read an integer */

11

printf( "Enter second integer\n" ); /* prompt */

12

scanf( "%d", &integer2 );

/* read an integer */

13

sum = integer1 + integer2;

/* assignment of sum */

14

printf( "Sum is %d\n", sum );

/* print sum */

8
9

15
16

return 0;

/* indicate that program ended successfully */

17 }
Enter first integer
45
Enter second integer
72
Sum is 117

3.

Another Simple C Program

As before
Comments, #include <stdio.h> and main

int integer1, integer2, sum;


Declaration of variables
Variables: locations in memory where a value can be stored

int means the variables can hold integers (-1, 3, 0, 47)


Variable names (identifiers)
integer1, integer2, sum
Identifiers: consist of letters, digits (cannot begin with a digit)
and underscores( _ )
Case sensitive

Declarations appear before executable statements


If an executable statement references and undeclared variable
it will produce a syntax (compiler) error

Another Simple C Program:

scanf( "%d", &integer1 );


Obtains a value from the user
scanf uses standard input (usually keyboard)

This scanf statement has two arguments


%d - indicates data should be a decimal integer
&integer1 - location in memory to store variable
& is the address of the variable name in scanf statements

When executing the program the user responds to the


scanf statement by typing in a number, then pressing the
enter (return) key

Another Simple C Program:

= (assignment operator)
Assigns a value to a variable
Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;

Variable receiving value on left

printf( "Sum is %d\n", sum );


Similar to scanf
%d means decimal integer will be printed
sum specifies what integer will be printed

Calculations can be performed inside printf statements


printf( "Sum is %d\n", integer1 + integer2 );

35

4. Variable Concepts
Variables
Variable names correspond to locations in the computer's
memory
Every variable has a name, a type, a size and a value
Whenever a new value is placed into a variable (through
scanf, for example), it replaces (and destroys) the previous
value
Reading variables from memory does not change them

A visual representation
integer1

45

36

5.

Arithmetic

Arithmetic calculations
Use * for multiplication and / for division
Integer division truncates remainder
7 / 5 evaluates to 1

Modulus operator(%) returns the remainder


7 % 5 evaluates to 2

Operator precedence
Some arithmetic operators act before others (i.e.,
multiplication before addition)
Use parenthesis when needed

Example: Find the average of three variables a, b and c


Do not use: a + b + c / 3
Use: (a + b + c ) / 3

37

Arithmetic operators:

Arithmetic

38

Rules of operator precedence:

C operation
Addition
Subtraction
Multiplication
Division
Modulus

Operator(s)
()

*, /, or %
+ or -

Operation(s)
Parentheses

Arithmetic
operator
+

*
/
%

Algebraic
expression
f+7
pc
bm
x/y
rmods

C expression
f
p
b
x
r

+
*
/
%

7
c
m
y
s

Order of evaluation (precedence)


Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses on the same level (i.e.,
not nested), they are evaluated left to right.
Multiplication,Divi Evaluated second. If there are several, they are
sion, Modulus
evaluated left to right.
Addition
Evaluated last. If there are several, they are
Subtraction
evaluated left to right.

6.

Decision Making: Equality and


Relational Operators

Executable statements
Perform actions (calculations, input/output of data)
Perform decisions
May want to print "pass" or "fail" given the value of a
test grade

if control structure
Simple version in this section, more detail later
If a condition is true, then the body of the if statement
executed
0 is false, non-zero is true

Control always resumes after the if structure

Keywords
Special words reserved for C
Cannot be used as identifiers or variable names

39

6.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Decision Making: Equality and Relational Operators

/* Fig. 2.13: fig02_13.c


Using if statements, relational
operators, and equality operators */
#include <stdio.h>

1. Declare variables

int main()
{
int num1, num2;

2. Input

printf( "Enter two integers, and I will tell you\n" );


printf( "the relationships they satisfy: " );
scanf( "%d%d", &num1, &num2 );
/* read two integers */

2.1 if statements

if ( num1 == num2 )
printf( "%d is equal to %d\n", num1, num2 );

3. Print

if ( num1 != num2 )
printf( "%d is not equal to %d\n", num1, num2 );
if ( num1 < num2 )
printf( "%d is less than %d\n", num1, num2 );
if ( num1 > num2 )
printf( "%d is greater than %d\n", num1, num2 );
if ( num1 <= num2 )
printf( "%d is less than or equal to %d\n",
num1, num2 );

40

41

6.
Decision Making: Equality and
Relational Operators
29
30
31

if ( num1 >= num2 )


printf( "%d is greater than or equal to %d\n",

32

num1, num2 );

33
34

return 0;

/* indicate program ended successfully */

35 }

Program Output
Enter two integers, and I will tell you
the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Enter two integers, and I will tell you
the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

6.

Decision Making: Equality and


Relational Operators

Standard algebraic
equality operator or
relational operator

C equality or
relational
operator

Example of C Meaning of C
condition
condition

==

x is equal to y

not =

!=

x == y
x != y

>
<

>
<

x > y
x < y

x is greater than y

>=

>=

x >= y

x is greater than or
equal to y

<=

<=

x <= y

x is less than or
equal to y

EqualityOperators

x is not equal to y

RelationalOperators

x is less than y

42

Keywords Of C

These are reserved words and should not be used for


variable names:
Keywords
auto
break
case
char
const
continue
default
do

double
else
enum
extern
float
for
goto
if

int
long
register
return
short
signed
sizeof
static

struct
switch
typedef
union
unsigned
void
volatile
while

43

You might also like