CSC 203
COMPUTER
PROGRAMMING I
COURSE OUTLINE
Introduction to problem solving methods and
Algorithms
Programming language elements (Syntax,
Semantics)
Variable Declaration, Data Types, Use of
Operators (Arithmetic, Assignment,
Increment/Decrement, Relational, Logic, etc)
Control structures of Algorithms
Introduction to C Programming language
Structural program development in C
C program control (Control structures in C)
C functions
C Arrays
C Pointers
COURSE OUTLINE
Course Lecturer:
Dr.A. Abayomi-Alli
(Coordinator)
Prof. A. S. Sodiya
INTRODUCTION TO PROGRAMMING
What is a program??? Differentiate between an
Algorithm and a Program!!!
A program is :
the implementation of an algorithm in a
programming language that can be executed by a
computer.
a sequence of instructions to instruct a computer
to perform specific tasks. Every program is written
in some programming language.
It can be executed several times, every time with
different inputs
Programs are commonly referred to as software.
Software is essential to a computer because it
controls everything the computer does. All of the
software that we use to make our computers
useful is created by individuals working as
programmers or software developers.
A programmer, or software developer, is a person
with the training and skills necessary to design,
create, and test computer programs.
What is Computer programming?
Computer programming is the act of writing
computer programs using a Computer Programming
Language to perform a specified task by the
computer.
There are thousands of programming languages
which can be used to write computer programs such
as Java, C, C++, Python, PHP, Perl, Ruby etc
Lady Ada Lovelace was an impressive
mathematician. She created a program for the
Analytical Engine. Based on this work, Ada is now
credited as being the first computer programmer
and, in 1979, a contemporary programming
language was named Ada in her honour.
Three levels of computer programming languages
may be distinguished:
1. Machine language
2. Assembly language
3. High-level language
Computers can only execute programs that are
written in machine language. A program can have
thousands or even millions of binary instructions,
and writing such a program would be very tedious
and time consuming.
Assembly language uses short words that are
known as mnemonics. For example, in assembly
language, the mnemonic add typically means to
add numbers, mul typically means to multiply
numbers, and mov typically means to move a
value to a location in memory.
Assembly language is close in nature to machine
language, and as such, both are called low-level
languages.
Assembly language also requires that you write a
large number of instructions for even the simplest
program like machine language.
A special program known as an assembler is used
to translate an assembly language program to a
machine language program.
A high-level language allows you to create
powerful and complex programs without writing
large numbers of low-level instructions. High-level
languages use words that are easy to understand
as English like expressions.
Language Description
Ada Ada was created in the 1970s, primarily for
applications used by the U.S.
Department of Defense.
BASIC Beginners All-purpose Symbolic
Instruction Code is a general-purpose
language that was originally designed in the
early 1960s to be simple enough for
beginners
to learn.
FORTRAN FORmula TRANslator was the first high-
level programming language. It was designed
in the 1950s for performing complex
mathematical calculations.
Language Description
COBOL Common Business-Oriented Language was
created in the 1950s, and was designed for
business applications.
Pascal Pascal was created in 1970, and was originally
designed for teaching programming. The
language was named in honor of the
mathematician, physicist, and philosopher
Blaise Pascal.
C and C++ C and C++ are powerful, general-purpose
languages developed at Bell Laboratories.
C# C# was created by Microsoft around the year
2000 for developing applications based on the
Microsoft .NET platform.
Java Java was created by Sun Microsystems in the
early 1990s.
JavaScript JavaScript, created in the 1990s, can be used
in web pages. Despite its name, JavaScript is
not related to Java.
Language Description
Ruby Ruby is a general-purpose language
that was created in the 1990s. It is
increasingly becoming a popular
language for programs that run on
web servers.
Visual Basic VB is a Microsoft programming
language and software development
environment that allows
programmers to create Windows-
based applications quickly.
There is NO best programming
language, each language has its
applications.
INTEGRATED DEVELOPMENT
ENVIRONMENT (IDE)
An IDE or Integrated Development Environment is
a
software program that is designed to help
programmers
and developers build software.
Most IDEs include:
a source code editor
a compiler
build automation tools
a debugger
SOFTWARE DEVELOPMENT
LANGUAGES
C
C++ (C-plus-plus)
C# (C-Sharp)
Pascal
Delphi
Visual Basic
WEB LANGUAGES
HTML (Hyper Text Markup Language)
XML (Extensible Markup Language)
Javascript
VBScript
PHP (Hypertext Preprocessor)
Java
ASP (Active Server Pages)
COMPILERS AND INTERPRETERS
Because the CPU understands only machine language
instructions, programs that are written in a high-level
language must be translated into machine language.
The programmer will use either a compiler or an
interpreter to make the translation.
A compiler is a program that translates a high-level
language program into a machine language program
and executes after.
An interpreter is a program that both translates and
executes the instructions line by line. As the
interpreter reads each individual instruction in the
program, it converts it to machine language
instructions and then immediately executes them.
FIGURE 1- COMPILING A HIGH-LEVEL PROGRAM AND
EXECUTING IT
FIGURE 2- EXECUTING A HIGH-LEVEL PROGRAM WITH
AN INTERPRETER
PHASES OF A COMPILER
1. Lexical analysis: This is the initial part of
reading and analysing the program text. The text
is read and divided into tokens, each of which
corresponds to a symbol in the programming
language, e.g., a variable name, keyword or
number.
2. Syntax analysis: This phase takes the list of
tokens produced by the lexical analysis and
arranges these in a tree-structure (called the
syntax tree) that reflects the structure of the
program. This phase is often called parsing.
3. Semantic analysis: This phase analyses the
syntax tree to check for errors. It resolves
semantic information.
PHASES OF A COMPILER
4.Intermediate code generation: The
program is translated to a simple machine
independent intermediate language.
5. Register allocation: The symbolic
variable names used in the intermediate
code are translated to numbers, each of
which corresponds to a register in the target
machine code.
6.Machine code generation: The
intermediate language is translated to
assembly language (a textual representation
of machine code) for a specific machine
architecture.
PHASES OF A COMPILER
7. Assembly and linking: The assembly-
language code is translated into binary
representation.
The first three phases are collectively called the
frontend of the compiler and the last three
phases are collectively called the backend. The
middle part of the compiler is the intermediate
code generation
DESIRABLE PROGRAM CHARACTERISTICS
Some important characteristics are expected in programs
written in any programming language.
1. Integrity. This refers to the accuracy of the
calculations. Programs will be meaningless if the
calculations are not carried out correctly. Thus, the
integrity of the calculations is an absolute necessity in
any computer program.
2. Clarity: refers to the overall readability of the
program, with particular emphasis on its
underlying logic. If a program is clearly written, it
should be possible for another programmer to follow the
program logic without undue effort. It should also be
possible for the original author to follow his or her own
program after being away from the program for an
extended period of time.
DESIRABLE PROGRAM CHARACTERISTICS
3. Simplicity. The clarity and accuracy of a
program are usually enhanced by keeping
things as simple as possible, consistent with the
overall program objectives.
4. Efficiency is concerned with execution speed
and efficient memory utilization. These are
generally important goals, though they should not
be obtained at the expense of clarity or simplicity.
DESIRABLE PROGRAM CHARACTERISTICS
5. Modularity: Many programs can be broken down
into a series of identifiable subtasks. It is a good
programming practice to implement each of these
subtasks as a separate program module. In C, such
modules are written as functions. The use of a modular
programming structure enhances the accuracy and
clarity of a program, and it facilitates future program
alterations.
6. Generality: Usually we will want a program to be
as general as possible, within reasonable limits.
For example, we may design a program to read in the
values of certain key parameters rather than placing
fixed values into the program. As a rule, a considerable
amount of generality can be obtained with very little
additional programming effort.
CONCEPT AND ROLE OF
ALGORITHM
An algorithm is a logical procedure to solve
a certain problem.
It is a sequence of elementary steps that an
execution machine must follow to solve a
problem.
It is simply the step-by-step procedure of
solving a problem.
Forexample, design an algorithm to find
the Sum and Average of n numbers.
CONCEPT AND ROLE OF
ALGORITHM
Algorithm
1. Start
2. Sum = 0
3. Input i, n
4. For (i = 1, n, i++)
5. Sum = Sum + i
6. ENDFOR
7. Output Sum
8. Average = Sum/n
9. Output Average
10. End
ASSIGNMENT:
REVISE NOTES ON ALGORITHMS (from CSC 102
class)!!!
Programming
language elements
(Syntax, Semantics)
SYNTAX AND SEMANTICS OF A PROGRAMMING
LANGUAGE
SYNTAX: It refers to the Grammar of the language,
the legal expressions and structure of the
language.
If a code contains a syntax error, it cannot be
translated. A syntax error is a mistake such as
mispelled keyword, a missing character, or in the
incorrect use of an operator. When this happens,
the compiler/interpreter displays an error message.
Examples of syntax error is:
j=4*(6-x;
i= /5; etc.
SEMANTICS: it refers to the meaning of the
expressions.
PROGRAMMING ERRORS
Three types of errors can occur when writing
programs:
1. Compiling errors (syntax error): these occurs
when the rules of the language have not been
followed. This may include a misspelt variable, a
forgotten brace, etc. Such statement cannot be
translated and the program cannot be executed.
2. Execution errors (run-time errors): Such
errors do not occur until the program is run. The
program may be syntactically correct, but still
contains mistakes that prevents it from
continuing normally when executed.
Occurs when the program directs the computer to
perform an illegal operation, such as dividing a
number by zero.
PROGRAMMING ERRORS
Logic errors (Design Error): This mistake can be
caused by faulty reasoning when designing the
program.
Its an error caused by following an incorrect
algorithm
Very difficult to detect - it does not cause run-
time error and does not display message
errors.
The only sign of logic error is an incorrect
program output
Can be detected by testing the program
thoroughly, comparing its output to calculated
results
To prevent, carefully check the algorithm and
written program before you actually type it.
Debugging: Process of removing errors from a
program
PROGRAMMING PARADIGMS
There are a number of alternative approaches to
the programming process, referred to as
Programming paradigms. Different paradigms
represents fundamentally different approaches to
building solutions to specific types of problems
using programming. Most programming languages
fall under one paradigm, but some languages
have elements of multiple paradigms.
Two of the most important programming
paradigms are the Procedural paradigm and
the Object-oriented paradigm.
STRUCTURED PROGRAMMING
Structured Programming: The principle idea
behind structured programming is the concept of
“divide and conquer”. Any task that is too
complex to be described simply is broken down
into a set of smaller component tasks until the
tasks are sufficiently small and self-contained
enough that each is easily understood.
As an example, computing the average salary of
an employee of a company can be broken down
into the following subtasks:
1. Count how many employees you have.
2. Find out what each employee earns.
3. Add all the salaries
4. Divide the total by the number of employees you
have.
STRUCTURED PROGRAMMING(CONT’D)
Totalling the salaries can be broken down into the
following subtasks.
1. Get each employee’s record.
2. Access the salary.
3. Add the salary to the running total.
4. Get the next employee’s record.
In turn, obtaining each employee’s record can be
broken down into the following:
5. Open the files of employees.
6. Go to the correct record.
7. Read the data.
PROCEDURAL PROGRAMMING
1.Procedural programming: is a programming
paradigm derived from structured programming
based upon the concept of the procedure call. It uses a
list of instructions to tell the computer what to do step-
by-step. Procedural programming relies on procedures,
also known as routines or subroutines. A procedure
contains a series of computational steps to be carried
out. Any given procedure might be called at any point
during a program's execution, including by other
procedures or itself.
Procedural programming is also referred to as Imperative
programming. Procedural programming languages are
also known as top-down languages.
Examples of procedural languages include Fortran,
OBJECT-ORIENTED PROGRAMMING
2. Object-Oriented programming: OOP provides
techniques for managing enormous complexity. It
is an approach to problem-solving where all
computations are carried out using objects. An
object is a component of a program that knows
how to perform certain actions and how to interact
with other elements of the program. Objects are
the basic units of object-oriented programming.
A simple example of an object would be a person.
Logically, you would expect a person to have a
name. This would be considered a property of the
person. You would also expect a person to be able
to do something, such as walking. This would be
considered a method of the person.
OBJECT-ORIENTED PROGRAMMING
Basically, objects have characteristics, also called
properties or attributes, such as name, age, colour
etc....They also have capabilities, also called
methods or functions.
A method in object-oriented programming is like a
procedure in procedural programming. The key
difference here is that the method is part of an
object. In object-oriented programming, you
organize your code by creating objects, and then
you can give those objects properties and you can
make them do certain things.
Examples of object-oriented languages include C#,
Java, Perl and Python.
Variable Declaration,
Data Types, Use of
Operators
(Arithmetic,
Assignment,
Increment/Decrement
, Relational, Logic,
VARIABLE DECLARATION
Variable: a name associated with a memory cell
whose value can change. Its simply a memory
storage.
Variable Declaration: specifies the data type of a
variable
Example: int num;
Variable Definition: assigning a value to the
declared variable
Example: int num = 5;
CONSTANTS
Entities that appear in the program code as fixed
values.
Any attempt to modify a CONSTANT will result in
error.
Major types of constants:
Integer constants
Positive or negative whole numbers with no fractional
part
Example:
const int MAX_NUM = 10;
const int MIN_NUM = -90;
CONSTANTS
Floating-point constants (float or double)
Positive or negative decimal numbers with
an integer part, a decimal point and a
fractional part
Example:
const double VAL = 0.5877e2; (stands for
0.5877 x 102)
const double pi = 3.412;
Character constants
A character enclosed in a single quotation
mark
Example:
const char letter = ‘n’;
const char number = ‘1’;
BASIC DATA TYPES
There are 4 basic data types :
int
float
double
Char
int
used to declare numeric program variables of
integer type
whole numbers, positive and negative
keyword: int
int number;
number = 12;
BASIC DATA TYPES
float
fractional parts, positive and negative
keyword: float
float height;
height = 1.72;
double
used to declare floating point variable of higher
precision or higher range of numbers
exponential numbers, positive and negative
keyword: double
double valuebig;
valuebig = 12E-3;
BASIC DATA TYPES
char
equivalent to ‘letters’ in English language
Example of characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z
Space (blank)
Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < >
etc
single character
keyword: char
char my_letter;
my_letter = 'U';
Qualifiers: short, long, unsigned, signed, const
ARITHMETIC OPERATORS
The major operators in any programming
language are + (Plus), - (Minus), * (Multiplication),
/(Division)
Others include:
Increment: a++
Example
int a=5;
a++ =6;
Modulus (remainder): %
Example:
12%5 = 2;
ARITHMETIC OPERATORS
Assignment by addition: +=
Example:
int a=4;
a+=1; (means a=a+1) value of a becomes 5
Comparison Operators: <, > , <=, >= , != (not equal), ==,
! (logical not), && (logical and), ||(logical or) .
Example:
int a=4, b=5;
a<b returns a true value.
Bitwise Operators: << (shift left), >>(shift right),
~(bitwise not), & (bitwise and), |(bitwise or) ,^ (bitwise
xor).
Example
int a=8;
OPERATOR PRECEDENCE
Meaning of a + b * c ?
Is it a+(b*c) or (a+b)*c ?
All operators have precedence over each other
*, / have more precedence over +, - .
Ifboth *, / are used, associativity comes into picture.
(more on this later)
Example :
5+4*3 = 5+12= 17.
PRECEDENCE TABLE
Highest on top
++ -- (Postfix)
++ -- (Prefix)
* / %
+ -
<< >>
< >
&
&&
||
THE COMMA OPERATOR
The operator enables you to put more than one
expression on a single line by separating each one
with a comma.
e.g int i = 10; j = 25;
CONTROL
STRUCTURES OF
ALGORITHMS
CONTROL STRUCTURES OF ALGORITHMS
What kinds of control structures are necessary in order to
describe algorithms?
(1) Sequence: This structure is the most elementary
structure. The sequence structure is a case where the steps
in an algorithm are constructed in such a way that, no
condition step is required.
For example, suppose you are required to design an
algorithm for finding the average of Six numbers, and the
sum of the numbers is given.
Algorithm:
1. Start
2. Input Sum
3. Average = Sum / 6
4. Output Average
5. Stop
CONTROL STRUCTURES OF ALGORITHMS
2) Selection: The selection structure also known as
decision structure is a case in the algorithm where
one has to make a choice of two alternatives by
making a decision depending on a given condition.
A selection structure takes the form:
If condition is true
Then do task A
else
Do TaskB
CONTROL STRUCTURES OF ALGORITHMS
The selection requires the following:
• Choose alternative actions as a result of testing a
logical condition
• Produce code to test a sequence of logical tests
In making choices, IF statement is used together with
logical operators to test for true or false.
The logical operators used are:
= is equal to <= is less than or
equal
> is greater than <> is not equal to
< is less than
>= is greater than or equal
IF STATEMENT
The If statement appears as follows:
if (condition)
{
statements;
}
-The statement is executed only if Condition is True
-If condition is false, the statement is ignored and the
next appropriate statement is simply executed.
e.g
If (sales > 5000)
{
bonus=500;
}
THE IF-ELSE STATEMENT
The If-else statement never appears in a program
without the If statement. The syntax is:
if (condition)
{
statements;
}
else
{
statements;
}
E.g
if (production > target)
{
target *=1.10;
}
else
{
target*=0.90;
}
CONTROL STRUCTURES OF ALGORITHMS
(3) Iteration: this requires repeating a block of
instructions until a logical event is verified or not.
The iteration structure can be implemented using
• Repeat Until Loop • The While Loop • The For
Loop
Any program instruction that repeats some
statement or sequence of statements a number of
times is called an iteration or a loop. The
commands used to create iterations or loops are all
based on logical tests.
CONTROL STRUCTURES OF ALGORITHMS
Repeat Until Loop
The syntax is
REPEAT
A statement or block of statements
UNTIL
a true condition
For example, A program repeatedly asking for an
entry of a number in the range 1 to 100 until a valid
number is entered.
REPEAT
Output “Enter a number between 1 and 100”
UNTIL
number >= 1 OR number <= 100
CONTROL STRUCTURES OF ALGORITHMS
THE WHILE LOOP
The second type of iteration. This type of conditional loop tests for
terminating condition at the beginning of the loop.
The syntax is:
WHILE (a condition is true)
A statement or block of statements
ENDWHILE
The while loop enables your programs to repeat a series of
statements, over and over, as long as a certain condition has not been
met. The format is:
while (condition)
{
statements;
}
CONTROL STRUCTURES OF ALGORITHMS
The For Loop: The third type of iteration. This, in its
simplest form, uses an initialisation of the variable as a
starting point, a stop condition depending on the value
of the variable. The variable is incremented on each
iteration until it reaches the required value.
The syntax is:
FOR (starting state, stopping condition, increment)
Statements
ENDFOR
For example:
FOR (n = 1, n <= 4, n++)
Output n
ENDFOR
FOR LOOP Cont’d
For (initialization; stopping condition; increment/decrement)
e.g
For (j=2; j<=80; j+=5)
For (i=10; i>=1; i--)
For (j=99; j>=0; j-=11)
THE DO-WHILE LOOP
It is similar to the while loop except the test condition occurs
at the end (rather than the beginning) of the loop. The
syntax of do-while is:
do
{
statements
}
while (condition)
CONTROL STRUCTURES OF ALGORITHMS
Introduction to
C Programming
language
HISTORY OF C
In 1972 Dennis Ritchie at Bell Labs writes C and
in 1978 the publication of The C Programming
Language by Kernighan & Ritchie caused a
revolution in the computing world
In 1983, the American National Standards
Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C.
The resulting definition, the ANSI standard, or
"ANSI C", was completed late 1988.
WHY IS C USEFUL?
C provides:
Efficiency, high performance and high quality
flexibility and power
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
BASICS OF C ENVIRONMENT
C systems consist of 3 parts
C development environment
Language
C Standard Library
C Development environment has 6 phases
Edit
Pre-processor
Compile
Link
Load
Execute
C DEVELOPMENT ENVIRONMENT
Program edited in
Editor and stored
Phase 1 Editor Disk on disk
Preprocessor
program processes
Phase 2 Preprocessor Disk the code
Creates object code
and stores on disk
Phase 3 Compiler Disk
Links object code
with libraries and
Phase 4 Linker Disk stores on disk
C DEVELOPMENT ENVIRONMENT
Primary memory
Puts program in
memory
Phase 5 Loader
Primary memory
Takes each instruction
and executes it storing
Phase 6 CPU new data values
C COMPILERS, LINKERS, LOADERS
FEW NOTES ON C PROGRAM…
C is a Structured programming language.
C is case-sensitive
Word, word, WorD, WORD, WOrD, worD, etc are all
different variables / expressions
Eg. sum = 23 + 7
What is the value of Sum after this addition ?
THE GENERAL FORM OF A SIMPLE PROGRAM
Simple C programs have the form
directives
int main ()
{
statements
}
C uses { and } in much the same way that some
other languages use words like begin and end.
Even the simplest C programs rely on three key
language features:
Directives
Functions
Statements
DIRECTIVES
Before a C program is compiled, it is first edited by a
preprocessor.
Commands intended for the preprocessor are called
directives.
Example:
#include <stdio.h>
<stdio.h> is a header containing information about
C’s standard I/O library.
Directives always begin with a # character.
By default, directives are one line long; there’s no
semicolon or other special marker at the end.
Two most common directives :
#include
#define
FUNCTIONS
Every C program consists of one or more modules called
FUNCTIONS. One of the functions must be called main where the
execution begins when the program is run.
A function is a self-contained module of code that can accomplish
some task.
A function is a sub-unit of a program that performs a specific
task.
Each function must contain:
a function heading
a list of argument declarations (arguments are also referred to
as parameters.
a block of statements, which is enclosed within a pair of braces
{ }
The braces may contain one or more elementary statements or
other block of statements.
i.e {
{
}
FUNCTIONS
The program will always begin by executing the
main function, which may access other functions.
Every function must return a value.
THE MAIN FUNCTION
The main function is mandatory.
main is special: it gets called automatically when
the program is executed.
main returns a status code; the value 0 indicates
normal program termination.
If there’s no return statement at the end of the
main function, many compilers will produce a
warning message.
STATEMENTS
A statement is a command to be executed when
the program runs.
Asking a function to perform its assigned task is
known as calling the function.
Each statement in C needs to be terminated
with semicolon (;)
Statement has two parts :
Declaration
The part of the program that tells the compiler
the names of memory cells in a program
Executable statements
Program lines that are converted to machine
language instructions and executed by the
computer
FEW NOTES ON C PROGRAM…
Comments
are inserted into the code using /* to start and */
to end a comment
Some compiler support comments starting with //
Such comments are useful in explaining the
underlying logic of various program features
They may appear anywhere within a program, as
long as they placed within delimiters /* and */
or //
Provides supplementary information but is ignored
by the preprocessor and compiler
/* Program to calculate the area of a circle*/
// This program was written by Iyabo Moshood
C SYNTAX
#include inserts another file. “.h” files are called
“header” files.
What do the <
> mean? This is a comment. The compiler
ignores this.
#include <stdio.h>
The main() function is
/* The simplest C Program */ always where your
int main(int argc, char **argv) program starts running.
{ Blocks of code (“lexical
printf(“Hello World\n”); scopes”) are marked by {
return 0; …}
}
Returning a value from Print out a message. ‘\n’ means “new
the function line”.
A QUICK DIGRESSION ABOUT THE COMPILER
#include <stdio.h>
/* The simplest C Program */
Compilation occurs in two steps:
int main(int argc, char **argv)
{
Preprocess “Preprocessing” and
printf(“Hello World\n”);
return 0;
“Compiling”
}
In Preprocessing, source code is “expanded”
__extension__ typedef
__extension__ typedef
unsigned long long int
unsigned int __uid_t;
__dev_t;
into a larger form that is simpler for the
compiler to understand. Any line that starts
__extension__ typedef unsigned int __gid_t;
__extension__ typedef unsigned long int __ino_t;
with ‘#’ is a line that is interpreted by the
__extension__ typedef unsigned long long int __ino64_t;
__extension__ typedef unsigned int __nlink_t;
__extension__ typedef long int __off_t;
__extension__ typedef long long int
extern void flockfile (FILE *__stream)
__off64_t;
;
Preprocessor.
extern int ftrylockfile (FILE *__stream) ;
extern void funlockfile (FILE *__stream) ;
int main(int argc, char **argv) • Include files are “pasted in” (#include)
{
printf(“Hello World\n”);
return 0;
• Macros are “expanded” (#define)
}
• Comments are stripped out ( /* */ , // )
• Continued lines are joined ( \ )
The compiler then converts the resulting
my_program text into binary code the CPU can run
Compile directly.
FUNCTIONS
A Function is a series of instructions to run.
You pass Arguments to a function and it
returns a Value.
“main()” is a Function. It’s only special
because it always gets called first when you
run your program.
Return type, or
void
Function
#include <stdio.h> Arguments
/* The simplest C Program */
int main(int argc, char **argv)
Calling a Function: “printf()” is just
{
another function, like main(). It’s
printf(“Hello World\n”); defined for you in a “library”, a
return 0; collection of functions you can call
} from your program.
Returning a
value
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.
Line 2: void main()
This statement declares the main function.
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.
Line 4: printf("Hello World \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.
Line 5: }
This closing bracket denotes the end of the program.
C PROGRAM STRUCTURE
Another example of simple program in C
#include <stdio.h>
int main()
{
printf(“I love programming\n”);
printf(“You will love it too once ”);
printf(“you know the trick\n”);
return 0;
}
THE OUTPUT
The previous program will produce the following
output on your screen
I love programming
You will love it too once you know the trick
INPUT/OUTPUT FUNCTIONS
A few functions that are pre-defined in the header
file <stdio.h> such as :
printf()
scanf()
getchar() & putchar()
1. The printf function
Used to send data to the standard output (usually the
monitor) to be printed according to specific format.
General format:
1.printf(“string literal”);
A sequence of any number of characters surrounded by
double quotation marks.
E.g printf(“Thank you\n”);
Thank you
THE PRINTF FUNCTION CONT…
2.printf(“format string”, variables);
Format string is a combination of text, format specifier
and escape sequence.
E.g printf (“Total sum is: %d\n”, sum);
Total sum is: 50
Assuming that
the value of sum
is 50
%d is a placeholder (format specifier)
marks the display position for a type integer variable
a common format identifier used in printf function.
\n is an escape sequence
moves the cursor to the new line
PLACEHOLDER / FORMAT SPECIFIER
No Format Specifier Output Type Output Example
1 %d Signed decimal integer 76
2 %i Signed decimal integer 76
3 %o Unsigned octal integer 134
4 %u Unsigned decimal integer 76
5 %x Unsigned hexadecimal (small letter) 9c
6 %X Unsigned hexadecimal (capital letter) 9C
7 %f Integer including decimal point 76.0000
8 %e Signed floating point (using e notation) 7.6000e+01
9 %E Signed floating point (using E notation) 7.6000E+01
10 %g The shorter between %f and %e 76
11 %G The shorter between %f and %E 76
12 %c Character ‘7’
13 %s String ‘76'
2. THE SCANF FUNCTION
Reads data from the standard input device (usually
keyboard) and stores it in a variable.
General format:
scanf(“format string”, &variable);
E.g scanf (“%d” , &a);
Ampersand (&) operator :
it passes the address of the variable
tells the scanf() where to find the variable to store the new
value
Format string is a combination of format specifier
and escape sequence (if any).
THE SCANF FUNCTION CONT…
Common Format Identifier used in printf and scanf
functions.
printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
Example
string %s %s
:
int age;
printf(“Enter your age:”);
scanf(“%d”, &age);
THE SCANF FUNCTION CONT…
If you want the user to enter more than one value,
you serialise the inputs.
Example:
float height, weight;
printf(“Please enter your height and weight:”);
scanf(“%f%f”, &height, &weight);
GETCHAR() AND PUTCHAR()
getchar() - read a character from standard
input
putchar() - write a character to standard output
Example: Please type a character: h
You have typed this character: h
#include <stdio.h>
int main
{
char my_char;
printf(“Please type a character:”);
my_char = getchar();
printf(“\nYou have typed this character: ”);
putchar(my_char);
return 0;
} 96
GETCHAR() AND PUTCHAR() CONT
Alternatively,
you can write the previous
code using normal printf / scanf and %c
placeholder.
Example
#include <stdio.h>
int main
{
char my_char;
printf(“Please type a character: ”);
scanf(“%c”,&my_char);
printf(“\nYou have typed this character: %c”, my_char);
return 0;
}
Please type a character: h
You have typed this character: h
A SIMPLE C PROGRAM
1 /* A first program in C */
2 #include <stdio.h>
3
4int main()
5 {
6 printf( "Welcome to C!\n" );
7
8 return 0;
9 }
Welcome to C!
Comments
Text surrounded by /* and */ is ignored by computer
Used to describe program
#include <stdio.h>
Preprocessor directive
Tells computer to load contents of a certain file
int 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
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
return 0;
A way to exit a function
return 0, in this case, means that the program terminated normally
Right brace }
Indicates end of main has been reached
A SIMPLE C PROGRAM
1 /* Addition program */
2 #include <stdio.h>
3
4 int main()
5 {
6 int integer1, integer2, sum; /* declaration */
7
8 printf( "Enter first integer\n" ); /* prompt */
9 scanf( "%d", &integer1 ); /* read an integer */
10 printf( "Enter second integer\n" ); /* prompt */
11 scanf( "%d", &integer2 ); /* read an integer */
12 sum = integer1 + integer2; /* assignment of sum */
13 printf( "Sum is %d\n", sum ); /* print sum */
14
15 return 0; /* indicate that program ended successfully */
16 }
OUTPUT
Enter first integer
45
Enter second integer
72
Sum is 117
1 /* Using if statements, relational
2 operators, and equality operators */
3 #include <stdio.h>
4
5 int main()
6 {
7 int num1, num2;
10
11 printf( "Enter two integers, and I will tell you\n" );
12 printf( "the relationships they satisfy: " );
13 scanf( "%d%d", &num1, &num2 ); /* read two integers */
14
15 if ( num1 == num2 )
16 printf( "%d is equal to %d\n", num1, num2 );
17
18 if ( num1 != num2 )
19 printf( "%d is not equal to %d\n", num1, num2 );
20
21 if ( num1 < num2 )
22 printf( "%d is less than %d\n", num1, num2 );
23
24 if ( num1 > num2 )
25 printf( "%d is greater than %d\n", num1, num2 );
26
27 if ( num1 <= num2 )
28 printf( "%d is less than or equal to %d\n",
29 num1, num2 );
30
31 if ( num1 >= num2 )
32 printf( "%d is greater than or equal to %d\n",
33 num1, num2 );
34
35 return 0; /* indicates program ended successfully */
36}
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
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
MORE EXAMPLES
#include <stdio.h>
// program prints a number of type int
int main()
{
int number = 4;
printf (“Number is %d”, number);
return 0;
}
Output: Number is 4
MORE EXAMPLES
#include <stdio.h>
// program reads and prints the same thing
int main()
{
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %d\n”, number);
return 0;
}
Output : Enter a number: 4
Number is 4
C TOKEN
Tokens are a series of continuous characters that
compilers treat as separate entities.
Tokens can be classified into:
1. Reserved words (also known as keywords)
2. Identifiers
3. Constants
4. String Literal
5. Punctuators
6. Operators
RESERVED WORDS
Keywords that identify language entities such
as statements, data types, language attributes,
etc.
Have special meaning to the compiler, cannot
be used as identifiers (variable, function name)
in our program.
Should be typed in lowercase.
Example: const, double, int, main, void, printf,
while, for, else (etc..)
IDENTIFIERS
Words used to represent certain program
entities (variables, function names, etc).
Example:
int my_name;
my_name is an identifier used as a program variable
void CalculateTotal
CalculateTotal is an identifier used as a function name
RULES FOR NAMING IDENTIFIERS
Rules Example
Can contain a mix of characters and numbers. H2o
However it cannot start with a number
First character must be a letter or underscore Number1;
_area
Can be of mixed cases including underscore XsquAre
character my_num
Cannot contain any arithmetic operators R*S+T
… or any other punctuation marks… #@x%!!
Cannot be a C keyword/reserved word struct; printf;
Cannot contain a space My height
… identifiers are case sensitive Tax != tax
CONSTANT EXAMPLE – VOLUME OF A
CONE
#include <stdio.h>
int main ()
{
const double pi = 3.412;
double height, radius, base, volume;
printf(“Enter the height and radius of the cone:”);
scanf(“%f %f”, &height, &radius);
base = pi * radius * radius;
volume = (1.0/3.0) * base * height;
printf(“\nThe volume of a cone is %f ”, volume);
return 0;
}
#DEFINE
You may also associate constant using #define
preprocessor directive
#include <stdio.h>
#define pi 3.142
int main ()
{
double height, radius, base, volume;
printf(“Enter the height and radius of the cone:”);
scanf(“%f %f”, &height, &radius);
base = pi * radius * radius;
volume = (1.0/3.0) * base * height;
printf(“\nThe volume of a cone is %f ”, volume);
return 0;
}
STRING LITERAL
A sequence of any number of characters
surrounded by double quotation marks “ ”.
Example of usage in C program:
printf(“What a beautiful day.\n”);
What a beautiful day.
Tohave double quotation marks as part of the
sentence, precede the quote with backslash
printf(“He shouted \“stop!\” to the thief.\n”);
He shouted “stop!” to the thief.
PUNCTUATORS (SEPARATORS)
Symbols used to separate different parts of the C
program.
These punctuators include:
[ ] ( ) { } , ; “: * #
Example:
#include <stdio.h>
int main ()
{
int num = 10;
printf(“%d”,num);
return 0;
}
MORE EXAMPLES
side1 = 4 - 1 = 3
side2 = 7 - 5 = 2
distance side12 side22
distance side12 side22
2 2
distance 3 2
distance 13 3.61
• Convert the above outlined solution to a
program in C
ARRAYS
The array is another kind of variable that is used
extensively in C.
An array is an identifier that refers to a collection of
data items that all have the same name. The data
items must all be of the same type (e.g., all
integers, all characters, etc.).
The individual data items are represented by their
corresponding array-elements, each element of
the array can be accessed referring to its position in
the array.
E.g Suppose that x is a 10-element array,
int x[10];
The first element is referred to as x[0] ,the second
as x[1] ,....,the last element will be x[9].
ONE-DIMENSIONAL ARRAY
E.g char charray [20];
The datatype is defined as char
The array name is charray
The array has 20 elements, indicated by [20]
Initializing one-dimensional array
An array can be defined as:
int var[5] = {10,20,30,40,50};
When initializing an array, all the elements must be
grouped within a pair of delimiters { } and must be
seperated by commas.
If there are more elements within delimiters than
indicated by the limit, a compiler error will result
e.g int var[5] = {1,2,3,4,5,6};
However, an array can have fewer elements than
the limit e.g int var[5] = {1,2,3,4};
-all shortages are set to 0 by default.
Sometimes, no number is supplied for the size of
an array, so the compiler counts the number of
items between delimiters and sets the array size to
that number e.g int var[ ] = {1,2,3,4};
MULTI-DIMENSIONAL ARRAY
Multidimensional arrays are defined in much the
same manner as one-dimensional arrays, except
that a separate pair of square brackets is required
for each array. Thus, a two-dimensional array will
require two
pairs of square brackets, a three-dimensional array
will require three pairs of square brackets, etc
Example: Consider a computer supplies where 2
sales representatives are employed. Considering 12
rows, one for each month of the year, and 2
columns, one for the sales rep. The array can be
represented as:
int sales [12][2];
You can declare 3 separate arrays for 6,12 or 18
elements:
int sales1 [6][2];
int sales2 [12][2];
int sales3 [18][2];
The #define directive can be used to define a
symbolic constant
#define LIMIT 18
int main ( )
{
int sales1 [6][2];
int sales2 [12][2];
int sales3 [18][2];
M X N 2-DIMENSIONAL ARRAY
Initializing multi-dimensional array
Considering an array where the months of the year are
divided into 4 seasons. This array definition has 4 rows
that represents the seasons and 3 elements in each
row to represent the 3 months in each season e.g
int seasons [4][3] = {
{3,4,5}, /*spring*/
{6,7,8}, /*summer*/
{9,10,11}, /*fall*/
{12,1,2} /*winter*/
};
The array representing the four seasons of the year
could be written like this:
int seasons[4][3] = {3,4,5,6,7,8,9,10,11,12,1,2};
Each element in the array can be accessed like this:
Seasons [1][2] contains the value 8
Seasons [2][0] contains the value 9
*Declaring a character array*
char arr [5] = {‘h’ , ‘e’, ‘l’, ‘l’, ‘o’};
*Declaring numeric array*
int arr [5] = {1,2,3,4,5};
PROGRAM TO CONVERT LOWERCASE TO
UPPERCASE TEXT
Here is a complete program that reads in a one-
dimensional character array, converts all of the
elements to uppercase, and then displays the
converted array.
/ * reads in a line of lowercase text to uppercase */
#include <stdio.h>
#include <ctype.h>
#define SIZE 80
int main ( )
{
char letter[SIZE] ;
int count ;
/ * read in the line */
for (count = 0; count < SIZE; ++count)
letter[count] = getchar();
/* display the line in upper case */
for (count = 0; count < SIZE; ++count)
put char ( toupper ( letter[count])) ;
}
PASSING AN ARRAY TO A FUNCTION
It is possible to pass an array to a function as an argument.
When declaring a one-dimensional array as a formal argument,
the array name is written with a pair of empty square brackets.
The size of the array is not specified within the formal
argument declaration.
Considering the fragment of a program below:
float average(int a, float x[ ]) ; /* function prototype
*/
int main( )
int n; /* variable DECLARATION */
float avg ; /* variable DECLARATION */
float list[100]; /* array DEFINITION */
.....
avg = average(n, list ) ;
.....
POINTERS
A pointer is a variable that represents the location
(rather than the value) of a data item, such as a
variable or an array element. Pointers are used
frequently in C, as they have a number of useful
applications. For example, pointers can be used to
pass information back and forth between a
function and its reference point.
A pointer is a variable that contains the address of
a variable. Pointers are also closely associated with
arrays and therefore provide an alternate way to
access individual array elements.
So if c is a char and p is a pointer that points to it,
it can be represented by:
To set a pointer to a variable’s address use & before
the variable as in,
x = &y;
In this example, x will now point to y, that is, x stores y’s
address, where & is a unary operator, called the
address operator, that evaluates the address of its
operand.
x, a pointer to y, referred to as a pointer variable.
since it “points” to the location where y is stored in
memory.
To get the value that x points to, use * (as in *x), where
* is a unary operator that operates only on a pointer
variable, called the indirection (or dereferencing)
operator, because it requires a second access, that is,
its a form of indirect addressing
All pointers are typed based on the type of entity that
they point to, e.g int *x;
So, if we write x = &y and U = *x, then U and y will
both represent the same value i.e the value of y will
indirectly be assigned to U.
Ex: Consider the simple C program shown below.
#include <stdio.h>
int main( )
int u1 , u2;
int a = 3;
int *b;
u1 = 2 * (a + 5 ) ; /* ordinary expression
b = &a; /* b points to a */
u2 = 2 * (*b + 5 ) ; /* equivalent
expression */
printf("\nu1=%d u2=%d", u1 , u2);
}
This program involves the use of two integer
expressions. The first, 2 * (a + 5), is an ordinary
arithmetic expression whereas the second, 2 * ( *b + 5
) , involves the use of a pointer. The expressions are
equivalent, since a and *b each represents the same
integer value.
The following output is generated when the program is
executed.
u1= 16 u2=16
EXAMPLE CODES
int x = 1, y = 2, z[10]; // z[10] is an array with 10 elements
int *ip; // ip is a pointer to an int, so it can point to x, y, or an
element of z
ip = &x; // ip now points at the location where x is stored
y = *ip; // set y equal to the value pointed to by ip, or y = x
*ip = 0; // now change the value that ip points to to 0, so now x = 0
// but notice that y is unchanged
ip = &z[0]; // now ip points at the first location in the array z
*ip = *ip + 1; // the value that ip points to (z[0]) is incremented
int x, *y, z, *q;
x = 3;
y = &x; // y points to x
printf("%d\n", x); // outputs 3
printf("%d\n", y); // outputs x’s address, will seem like a random number
to us
printf("%d\n", *y); // outputs what y points to, or x=3
printf("%d\n", *y+1); // outputs 4 (print out what y points to + 1)
printf("%d\n", *(y+1)); // this outputs the item after x in memory –
what is it?
USING POINTERS WITH ARRAYS
Considering ip = &z[0];
-this sets the pointer to point at the first element of the array
What about accessing z[1]?
1 can be added to the location pointed to by ip i.e, *(ip+1)
Array Example Using a Pointer
int x[4] = {12, 20, 39, 43}, *y;
y = &x[0]; // y points to the beginning of the array
printf("%d\n", x[0]); // outputs 12
printf("%d\n", *y); // also outputs 12
printf("%d\n", *y+1); // outputs 13 i.e (12 + 1)
printf("%d\n", (*y)+1); // also outputs 13
printf("%d\n", *(y+1)); // outputs x[1] or 20
y+=2; // y now points to x[2]
printf("%d\n", *y); // prints out 39
*y = 38; // changes x[2] to 38
printf("%d\n", *y-1); // prints out x[2] – 1 = 37
*y++; // sets y to point at the next array element
printf("%d\n", *y); // outputs x[3]=43
(*y)++; // sets what y points to to be 1 greater
printf("%d\n", *y); // outputs the new value of x[3] =44