Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

CET 04207

COMPUTER PROGRAMMING

Facilitator: Liberatus Sago

1
References
• C Programming For The Absolute Beginner,
Second Edition. Michael Vine
• C For Dummies 2nd Edition. Dan Gookin

2
Topic One: Introduction

3
What is a Computer?
• An electronic device for storing and processing
data, typically in binary form, according to
instructions given to it in a variable program.
• From the above definition we see that
computer can process data in binary form only
(series of 0s and 1s).

4
Communicating with
a Computer
• Communication cycle
– One complete unit of communication.
• An idea to be sent.
• An encoder. Speaker encodes Listener decodes
information information
• A sender.
• A medium.
• A receiver.
• A decoder.
• A response. Listener returns
feedback to speaker

5
Communicating with
a Computer

• Substituting a computer
for one of the people in User encodes
information Computer decodes
the communication information
process.
– Process is basically
the same. Computer
returns
• Response may be symbols results
on the monitor. to user

6
Communicating with
a Computer
A breakdown can occur any place along the cycle...

• Between two people: • Between a person and a


– The person can’t hear you. computer:
– The phone connection is – The power was suddenly
broken in mid-call. interrupted.
– One person speaks only – An internal wire became
French, while the other only disconnected.
Japanese. – A keyboard malfunctioned.

When communicating instructions to a computer, areas


of difficulty are often part of the encoding and decoding
process.

7
Computer Programming
• Programming languages bridge the gap between human
thought processes and computer binary circuitry.
• Computer programming (often shortened to programming)
is a process that leads from an original formulation of a
computing problem to executable computer programs.
• Programming language: A series of specifically defined
commands designed by human programmers to give
directions to digital computers.
• Commands are written as sets of instructions, called
programs.
• All programming language instructions must be expressed
in binary code before the computer can perform them.

8
The Role of Languages in Communication

• Three fundamental elements of language that


contribute to the success or failure of the
communication cycle:
– Semantics
– Syntax
– Participants

9
 Semantics: Refers to meaning.
• Human language: • Computer language:
– Refers to the meaning of – Refers to the specific
what is being said. command you wish the
– Words often pick up computer to perform.
multiple meanings. • Input, Output, Print
– Phrases sometimes have • Each command has a
idiomatic meanings: very specific
• let sleeping dogs lie meaning.
(don’t aggravate the • Computers associate
situation by “putting one meaning with
in your two cents”) one computer
command.

10
 Syntax: Refers to form, or structure.

• Human language: • Computer language:


– Refers to rules governing
– Refers to rules governing
grammatical structure.
exact spelling and
• Pluralization, tense, punctuation, plus:
agreement of subject and
• Formatting, repetition,
verb, pronunciation, and
subdivision of tasks,
gender.
identification of variables,
– Humans tolerate the use of definition of memory
language. spaces.
• How many ways can you – Computers do not tolerate
say no? Do they have the syntax errors.
same meaning?

11
 Participants:
• Human languages are used by people to communicate with each other.
• Programming languages are used by people to communicate with machines.

• Human language:
• Computer language:
– In the communication cycle, humans can
– People use programming languages.
respond in more than one way.
– Programs must be translated into
• Body language
binary code.
• Facial expressions
– Computers respond by performing
• Laughter the task or not!
• human speech

12
Brief History of Computer Programming
• In the Beginning, early computers consisted of
special-purpose computing hardware.
– Each computer was designed to perform a particular
arithmetic task or set of tasks.
– Skilled engineers had to manipulate parts of the
computer’s hardware directly.
• Some computers required “fat-fingering”.
– Fat-fingering: Engineer needed to position electrical relay switches manually.
• Others required programs to be hardwired.
– Hardwiring: Using solder to create circuit boards with connections needed to
perform a specific task.

13
• ENIAC
– Used programs to
complete a number of
different mathematical
tasks.
• Programs were entered
by plugging connector
cables directly into
sockets on a plug-in
board.
– Set-up could take hours.
– A program would
generally be used for
weeks at a time.

14
• In the beginning in order to use a computer, you
needed to know how to program it. But today that is
not the case
• To see how this was accomplished, lets see the
evolution of programming languages.
– First Generation - Machine Language (code)
– Second Generation - Assembly Language
– Third Generation - People-Oriented Programming
Languages
– Fourth Generation - Non-Procedural Languages
– Fifth Generation - Natural Languages

15
First Generation - Machine Language (code)
– Machine language programs were made up of
instructions written in binary code.
• This is the “native” language of the computer.
• Each instruction had two parts: Operation code,
Operand
– Operation code (Opcode): The command part of a computer
instruction.
– Operand: The address of a specific location in the computer’s
memory.
• Hardware dependent: Could be performed by only one
type of computer with a particular CPU.

16
Second Generation - Assembly Language
– Assembly language programs are made up of
instructions written in mnemonics.
– Mnemonics: Uses convenient alphabetic
abbreviations to represent operation codes, and
abstract symbols to represent operands.
– Each instruction had two parts: Operation code,
Operand
– Hardware dependent.
– Because programs are not written in 1s and 0s, the
computer must first translate the program before it
can be executed.

17
• READ num1
• READ num2
• LOAD num1
• ADD num2
• STORE sum
• PRINTsum
• STOP

18
• Third Generation - People-Oriented Programs
– Instructions in these languages are called
statements.
• High-level languages: Use statements that resemble
English phrases combined with mathematical terms
needed to express the problem or task being
programmed.
• Transportable: NOT-Hardware dependent.
• Because programs are not written in 1s and 0s, the
computer must first translate the program before it can
be executed.

19
• Pascal Example: Read in two numbers, add
them, and print them out.
Program sum2(input,output);
var
num1,num2,sum : integer;

begin
read(num1,num2);
sum:=num1+num2;
writeln(sum)
end.

20
• Fourth Generation - Non-Procedural
Languages
– Programming-like systems aimed at simplifying
the programmers task of imparting instructions to
a computer.
– Many are associated with specific application
packages.
• Query Languages:
• Report Writers:
• Application Generators:

21
– Query Languages:
• Enables a person to specify exactly what information they
require from the database.
• Usually embedded within database management programs.
– Report Writers:
• Takes information retrieved from databases and formats into
attractive, usable output.
– Application Generators:
• A person can specify a problem, and describe the desired
results.
• Included with many micro-computer programs (macros).

22
• Fourth Generation - Non-Procedural Languages
(cont.)
– Object-Oriented Languages: A language that
expresses a computer problem as a series of objects a
system contains, the behaviors of those objects, and
how the objects interact with each other.
• Object: Any entity contained within a system.
– Examples:
» A window on your screen.
» A list of names you wish to organize.
» An entity that is made up of individual parts.
• Some popular examples: C++, Java, Smalltalk, Eiffel.

23
• Fifth Generation - Natural Languages
– Natural-Language: Languages that use ordinary
conversation in one’s own language.
• Research and experimentation toward this goal is being
done.
– Intelligent compilers are now being developed to translate
natural language (spoken) programs into structured machine-
coded instructions that can be executed by computers.
– Effortless, error-free natural language programs are still some
distance into the future.

24
Individual Assignment
• What are the differences between Object
Oriented Programming and Structured
Programming?

25
Common programming languages
Fortran
Cobol
Basic
Pascal
C
C++
Java
Vb
Php

26
C Programming Language
• C programming language is a general-purpose, high-
level language that was originally developed by Dennis
M. Ritchie to develop the UNIX operating system at
Bell Labs.
• It was originally first implemented on the DEC PDP-11
computer in 1972.
• In 1978, Brian Kernighan and Dennis Ritchie produced
the first publicly available description of C, now known
as the K&R standard.
• The UNIX operating system, the C compiler, and
essentially all UNIX applications programs have been
written in C.

27
• C was invented to write an operating system
called UNIX.
• C is a successor of B language, which was
introduced around 1970.
• The UNIX OS was totally written in C by 1973.
• Today, C is the most widely used and popular
System Programming Language.
• Most of the state-of-the-art software have been
implemented using C.
• Today's most popular Linux OS and RDBMS
MySQL have been written in C.

28
• The C has now become a widely used
professional language for various reasons
which are;
o Easy to learn
o Structured language
o It produces efficient programs.
o It can handle low-level activities.
o It can be compiled on a variety of computer
platforms.

29
C development life cycle
Step 1: Use an editor to write your source code. By
tradition, C source code files have the extension .C
(for example, MYPROG.C, DATABASE.C, and so on).
The source code file is a text file on disk. The file
contains instructions for the computer that are
written in the C programming language.

30
• Step 2: Compile the program using a compiler. If
the compiler doesn't find any errors in the
program, it produces an object file. The compiler
produces object files with an .OBJ extension and
the same name as the source code file (for
example, MYPROG.C compiles to MYPROG.OBJ).
If the compiler finds errors, it reports them. You
must return to step 1 to make corrections in your
source code.
• Compiler is a special program that reads the
instructions stored in the source code file,
examines each instruction, and then translates
the information into the machine code
understood only by the computer’s
microprocessor.
31
Step 3: Link the program using a linker. If no errors
occur, the linker produces an executable program
located in a disk file with an .EXE extension and the
same name as the object file (for example,
MYPROG.OBJ is linked to create MYPROG.EXE).

32
• Step 4: Execute the program. You should test
to determine whether it functions properly. If
not, start again with step 1 and make
modifications and additions to your source
code.

33
Example 1
#include <stdio.h>
main( )
{
printf(“This is my first C - program”);
return 0;
}

34
Example 2
#include <stdio.h>
main( )
{
printf(“Hello World”);
printf(“This is my first C - program”);
}

35
Exercise
Write a program to display First and Second
names, Age, Gender and address. Save the file
as MyParticulars

36
The Components of a C Program
• A Short C Program
• The Program's Components
– The main() Function
– The #include Directive
– The Variable Definition
– Program Statements
– The Function Definition
– Program Comments
– Braces
– Running the Program
37
Every C program consists of several components
combined in a certain way. To get the overall
picture, however, you should begin by seeing a
complete (though small) C program with all its
components identified.

38
A Short C Program
• The program below presents the source code
for MULTIPLY.C. This is a very simple program.
All it does is input two numbers from the
keyboard and calculate their product. At this
stage, don't worry about understanding the
details of the program's workings. The point is
to gain some familiarity with the parts of a C
program.

39
Before looking at the sample program, you need to
know what a function is, because functions are central
to C programming.
A function is an independent section of program code
that performs a certain task and has been assigned a
name. By referencing a function's name, your program
can execute the code in the function. The program also
can send information, called arguments, to the function,
and the function can return information to the main
part of the program.
The two types of C functions are library functions,
which are a part of the C compiler package, and user-
defined functions, which you, the programmer, create.
You will learn about both types of functions in the next
sections.
40
/*The program to calculate the product of two
numbers. */
#include <stdio.h>
main()
{
int a, b, c;
/* Input the first number */
printf("Enter a first number: ");
scanf("%d", &a);

41
/* Input the second number */
printf("Enter another number: ");
scanf("%d", &b);
/* Calculate and display the product */
c = a*b;
printf (“The product of two numbers is %d”, c);
return 0;
}
Enter a first number: 5
Enter another number: 20
The product of two numbers is 100 42
/*The program to calculate the product of two numbers. */
#include <stdio.h>
main()
{
int a, b, c;
/* Input the first number */
printf("Enter a first number: ");
scanf("%d", &a);
/* Input the second number */
printf("Enter another number: ");
scanf("%d", &b);
/* Calculate and display the product */
c = a*b;
printf (“The product of two numbers is %d”, c);
return 0;
}
43
The Program's Components
The following are the various components of the
preceding sample program.

44
The main() Function
The only component that is required in every C
program is the main() function. In its simplest form,
the main() function consists of the name main
followed by a pair of empty parentheses (()) and a
pair of braces ({}). Within the braces are statements
that make up the main body of the program. Under
normal circumstances, program execution starts at
the first statement in main() and terminates at the
last statement in main().

45
The #include Directive
• The #include directive instructs the C compiler to
add the contents of an include file into your
program during compilation. An include file is a
separate disk file that contains information
needed by your program or the compiler. Several
of these files (sometimes called header files) are
supplied with your compiler. You never need to
modify the information in these files; that's why
they're kept separate from your source code.
Include files should all have an .H extension (for
example, STDIO.H).
46
• You use the #include directive to instruct the
compiler to add a specific include file to your
program during compilation. The #include
directive in this sample program means "Add
the contents of the file STDIO.H." Most C
programs require one or more include files.
• The library name stdio.h is short for standard
input output and contains links to various
standard C library functions, such as printf().

47
The Variable Definition
• A variable is a name assigned to a data
storage location. Your program uses variables
to store various kinds of data during program
execution. In C, a variable must be defined
before it can be used. A variable definition
informs the compiler of the variable's name
and the type of data it is to hold.
• In the sample program, the definition on line,
int a,b,c; , defines three variables--named a, b,
and c--that will each hold an integer value. 48
Program Statements
• The real work of a C program is done by its
statements. C statements display information on-
screen, read keyboard input, perform mathematical
operations, call functions, read disk files, and carry
out all the other operations that a program needs to
perform.
• Remember that in your source code, C statements
are generally written one per line and always end
with a semicolon. The statements in MULTIPLY.C are
explained briefly in the following sections.
49
• Most program statements control program
execution and functionality and may require a
program statement terminator (;).
• Program statements that do not require a
terminator include preprocessor directives,
comment blocks, and function headers.

50
printf()
• The printf() statement is a library function that
displays information on-screen. The printf()
statement can display a simple text message
or a message and the value of one or more
program variables.
• The function is called printf() for a reason.
The f stands for formatted. The advantage of
the printf function over other, similar display-
this-or-that functions in C is that the output
can be formatted.
printf(“format_string”[,var[,...]]);
51
• What appears in the double quotes is really a
formatting string. It’s still text that appears in printf()’s
output, but secretly inserted into the text are various
conversion characters, or special “placeholders,” that
tell the printf() function how to format its output and
do other powerful stuff.
• After the format string comes a comma (still inside the
parentheses) and then one or more items called
arguments. The argument shown in the preceding
example is var, which is short for variable. We can use
printf() to display the content or value of one or more
variables. We do this by using special conversion
characters in format string.
52
scanf()

• The scanf() statement is another library


function. It reads data from the keyboard and
assigns that data to one or more program
variables.

53
The return statement

• All functions in C can return values. For instance, when you


make a function to add two numbers, you can make such a
function that returns to you the value of the addition.
• The main() function itself returns a value. By default, main()
returns an integer. In C, integers are decimal numbers
without fraction portions.
• Therefore, in the program, there is a statement, return 0;,
that indicates that 0 is returned from the main() function
and the program is terminated normally.
• A nonzero value returned by the return statement tells the
operating system that an error has occurred. The bigger the
return value, the more severe the error.

54
The Function Definition
• A function is an independent, self-contained section of code that is
written to perform a certain task. Every function has a name, and
the code in each function is executed by including that function's
name in a program statement. This is known as calling the function.
• There are two types of functions: User-defined & Library.
• The user-defined function: As the name implies, user-defined
functions are written by the programmer during program
development.
• The library functions that are a part of the C compiler package.
Library functions perform most of the common tasks (such as
screen, keyboard, and disk input/output) your program needs. In
the sample program, printf() and scanf() are library functions.

55
• Functions allow you to group a logical series of
activities, or program statements, under one
name
• Each function implementation requires that
you use a beginning brace ({) and a closing
brace (})

56
Program Comments
Any part of your program that starts with /* and ends with */
is called a comment. The compiler ignores all comments, so
they have absolutely no effect on how a program works. You
can put anything you want into a comment, and it won't
modify the way your program operates. A comment can span
part of a line, an entire line, or multiple lines. Here are three
examples:
/* A single-line comment */
int a,b,c; /* A partial-line comment */
/* a comment
spanning
multiple lines */

Comments help to identify program purpose and explain


complex routines

57
Braces

• You use braces ({}) to enclose the program


lines that make up every C function--including
the main() function. A group of one or more
statements enclosed within braces is called a
block. As you will see in later chapters, C has
many uses for blocks.

58
Keywords
• There are 32 words defined as keywords in the
C programming language. These keywords
have predefined uses and cannot be used for
any other purpose in a C program. These
keywords are used by the compiler as an aid
to building the program.
• Note that these keywords must always be
written in lowercase

59
Keyword Description
auto Defines a local variable as having a local lifetime
break Passes control out of the programming construct
case Branch control
char Basic data type
const Unmodifiable value
continue Passes control to loop’s beginning default Branch control
do Do While loop
double Floating-point data type
else Conditional statement
enum Defines a group of constants of type int
extern Indicates an identifier as defined elsewhere
float Floating-point data type
for For loop
goto Transfers program control unconditionally
if Conditional statement
int Basic data type 60
long Type modifier
register Stores the declared variable in a CPU register
return Exits the function
short Type modifier
signed Type modifier
sizeof Returns expression or type size
static Preserves variable value after its scope ends
struct Groups variables into a single record
switch Branch control
typedef Creates a new type
union Groups variables that occupy the same storage space
unsigned Type modifier
void Empty data type
volatile Allows a variable to be changed by a background routine
while Repeats program execution while the condition is true

61
Escape Sequences
• Escape sequences are specially sequenced
characters used to format output.
• When combined with the backslash (\), special
characters such as n, t, r, ‘ and “ make up an
escape sequence.
Escape Sequence Purpose
\n Creates a new line
\t Moves the cursor to the next tab
\r Moves the cursor to the beginning of
the current line
\\ Inserts a backslash
\" Inserts a double quote
\' Inserts a single quote
62
Escape Sequence \n
• This particular escape sequence (\n) tells the
program to add a new line.
• Take a look at the following program
statement. How many new lines are added to
standard output with these printf()
statements?
printf("\nC you later\n");
printf("line 1\nline2\nline3\n");

63
Escape Sequence \t
• Escape sequence \t moves the cursor to the next tab
space. This escape sequence is useful for formatting
output in many ways. For example, a common
formatting desire is to create columns in your output,
as the following program statements demonstrate.
printf("\nSun\tMon\tTue\tWed\tThu\tFri\tSat\n");
printf("\t\t\t\t1\t2\t3\n");
printf("4\t5\t6\t7\t8\t9\t10\n");
printf("11\t12\t13\t14\t15\t16\t17\n");
printf("18\t19\t20\t21\t22\t23\t24\n");
printf("25\t26\t27\t28\t29\t30\t31\n");

64
Escape Sequence \\
• Escape sequence \\ inserts a backslash into
your text. This may seem unnecessary at first,
but remember that whenever the program
reads a backslash in a printf() function, it
expects to see a valid escape character right
after it. In other words, the backslash
character (\) is a special character in the
printf() function; if you need to display a
backslash in your text, you must use this
escape sequence.

65
• The following program statement
demonstrates escape sequence \\.
printf("c:\\cygwin\\bin must be in your system
path");
The output is
c:\cygwin\bin must be in your system path

66
Escape Sequence \”
• Another reserved character in the printf()
function is the double quote (") character. To
insert a quote into your outputted text, use
the escape sequence \" as demonstrated in
the following program statement.
printf("\"This is quoted text\"");
• The output is
“This is quoted text”

67
Escape Sequence \’
• Similar to the double quote escape sequence
(\") is the single quote (also called an
apostrophe) escape sequence (\'). To insert a
single quote into your outputted text, use the
escape sequence \' as demonstrated in the
following program statement
printf("\nA single quote looks like \'\n");
• The output is
A single quote looks like ‘
68
Common Errors
• The following are some of the common errors
that many beginner programmers can
encounter during compiling the source code.
– Missing Program Block Identifiers
– Missing Statement Terminators
– Invalid Preprocessor Directives
– Invalid Escape Sequences
– Invalid Comment Blocks

69
• A single error at the top of your program can
cause a lot of errors to be seen during compile
time.
• The best place to start debugging compile
errors is with the first error

70
Exercise
1) Create a program that prints your name.
2) Create a program that uses escape sequence \" to print your favorite
quote.
3) Create a program that uses escape sequence \\ to print the following
directory structure: c:\cygwin\home\administrator.
4) Write a program that prints a diamond as demonstrated next.
*
* *
* *
* *
* *
* *
*
5) Create a calendar program using the current month (similar to the one
shown in Slide No. 62).

71

You might also like