Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 99

COMPUTER

PROGRAMMING FOR
ENGINEERS – CENG 205

Tweneboah-Koduah Samuel
? MEng. - ICE  BSc. - TE 
D o l p h i n z 05/07/2024
Te l e n e t w o r k s C o m p a n y CENG 205 1
QUOTE
This mind is not an empty vessel to be filled
but a powerhouse to be ignited
– Plutarch

“All progress is born of inquiry. Doubt


is often better than overconfidence, for
it leads to inquiry, and inquiry leads to
invention” – Hudson Maxim
05/07/2024 CENG 205 2
COURSE OUTLINE
Objective/Purpose
The course is to equip students with knowledge and skills in
applying computer-programming methods to solve engineering
problems.
Principal Outcomes - On completion:
 Develop an algorithm that will solve a given (simple)
problem
 Explain the operation of the standard algorithm control-
constructs. Understand the fundamentals of computer
programming for engineering application, Understand the
use of objects, input/output streams
 Translate an algorithm into C/C++
 Run and debug programs, etc.
Introduction to Matlab, m-files
05/07/2024 CENG 205 3
COURSE OUTLINE
Assessment
40%
Assignment and Quizzes: 5
Mid-Sem: 20
Attendants: 5
Mini-project:10
Exams – 60%
Total 100%
05/07/2024 CENG 205 4
ASSUMPTIONS ABOUT
YOU!
That you have no prior knowledge
in any (computer) programming
language else this course will be an
added advantage and such a person
is encouraged to make meaningful
contributions.

05/07/2024 CENG 205 5


RECOMMENDED BOOKS
 Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy
Sierra & Elisabeth Robson. Head First Design Patterns
 Aaron R. Bradley. Programming for Engineers: A
Foundational Approach to Learning C and Matlab
 Jeri R. Hanly & Elliot B. Koffman. Problem solving and
program design in C**
 Byron S. Gottfried. Schaum's Outline of Programming
with C**
 Kjell Backman. Structured programming with C-plus-
plus**
05/07/2024 CENG 205 6
HISTORY OF COMPUTERS
& SOFTWARE
Computers makes life easy
Microwave
Smartphones
ATMs, etc.

Computer program (software) is


essential
Computer useless without list of instructions to
follow
Programming language (C, Python, Java, C#, C++,
Matlab, etc. ) way to communicate with
05/07/2024 CENG 205 7
HISTORY OF COMPUTERS
& SOFTWARE
1930s – First electronic computer
By Dr. John Atanasoff and Clifford Bery Iowa
State University
1946 – Univ. of Pennsylvania
ENIAC (Electronic Numerator, Integrator, Analyzer
and Computer) uses vacuum tubes as basic
electronic components
EDVAC (Electronic Discrete Variable Computer),
incorporating many of the ideas of John von
Neumann

05/07/2024 CENG 205 8


HISTORY OF COMPUTERS
& SOFTWARE
Computer?
Current electronic components – ICs
Contains over billions of transistors
Fast and reliable
Cheap, etc.
Hardware – CPU, monitor, keyboard,
mouse, etc.
Software – programs or instruction that
help solve problems with a computer
05/07/2024 CENG 205 9
WHY WOULD YOU CARE ABOUT
PROGRAMMING?
m e s
t o u tc o
t p r e d ic
s th a
e n t l i fe
x pe r im a i ly
r m e y d
Perfo Solve Engineering f m
o Problems
a r t
re p
r s a
t e It’s cool, and it
p u
o m makes me feel smart
C

Programming is beautiful Get a great job


05/07/2024 CENG 205 10
05/07/2024 CENG 205 11
Robotics

05/07/2024 CENG 205 12


Program robots, so I don’t have to vacuum

Create a portable
electronic toilet

05/07/2024 CENG 205 13


COMPUTER- HARDWARE
Computer Architecture
Main Input/Output
Memory Devices

Central Processing
Mass Unit (CPU) Communication
storage Device

05/07/2024 CENG 205 14


PRIMARY TASK OF
HARDWARE
Move electrons around

No intelligence of its own, No


will, No knowledge!
05/07/2024 CENG 205 15
OVERVIEW OF COMPUTER - SOFTWARE
Computer Software
Operating System: Software
Periphera
for managing coordinating the l Control
hardware resources
Peripheral Control: Software
for I/O with CPU (drivers)
Memory Management:
Manage the system memory Operating
Software Management (flow
control): Manage processes, System
priorities, multitasking Memory Software
Applications: Word managem Managem
ent ent
processing,
chatting, browsing, etc.
05/07/2024 CENG 205 16
PRIMARY TASK OF SOFTWARE
Tell the hardware what to do (how to
move the electrons around)

soft Hard
ware ware

05/07/2024 CENG 205 17


SCHEMATIC OF (MODERN)
COMPUTERS
Step 1: Program is stored in the memory
Memory

Step 2: Instructions are read by the CU


Control Arithmetic
Unit Logic Unit
Step 3: Data is moved to the ALU
(ALU)

Clock
Step 4: Data is processed by the ALU

Step 5: Data is redirected to memory (or other peripheral


devices)

Relying on a set of instructions for performing Arithmetic


Operations
05/07/2024 CENG 205 18
THE BIG PICTURE
CENG 205

Algorith
Problem Language
m

Voltage
Machine
in
code
circuitry
05/07/2024 CENG 205 19
SOFTWARE DESIGN
Flowchart/algorithms
Algorithms – an algorithm is any well-
defined computational procedure that takes
some value, or set of values, as input and
produces some value, or set of values as
output
It’s the first step of the solution process of
any problem after analysis.
Flowchart is graphical representation of
algorithms – sequence of events to occur in
order to accomplish a given task.
05/07/2024 CENG 205 20
ALGORITHMS AND DATA
STRUCTURES
Sorting by insertion-
example
Input: sequence of numbers
Output: A permutation
(reordering) of the input
such that

05/07/2024 CENG 205 21


ALGORITHMS/DATA
STRUCTURES
Sorting by insertion- example

Operation of Insertion-Sort on array = (5, 2, 4, 6, 1, 3)

05/07/2024 CENG 205 22


ALGORITHMS/DATA
STRUCTURES
Sorting by insertion- example
Pseudo code

05/07/2024 CENG 205 23


ALGORITHMS/DATA
STRUCTURES
Sorting by merge-sort example

05/07/2024 CENG 205 24


ALGORITHMS/DATA
STRUCTURES
Efficiency – Insertion-sort and merge-
sort
Algorithms differ from one another even though they
solve the same problem in terms of speed and
efficiency.
Insertion-sort takes time ~ (seconds per say), where
k is constant that does not depend on n
Merge-sort takes , where c is constant that does not
depend on n
. Insertion-sort has a factor of n whereas merge-
sort: 
Insertion-sort run fast than merge-sort for small
value of n
05/07/2024 CENG 205 25
ALGORITHMS/DATA
STRUCTURES
Efficiency – Insertion-sort and
Example: Find the time required for merge-
sort
a) computer
Algorithms differAfrom
required to sort
one another even10
though they
solvemillion
the samenumber
problem inusing
terms insertion-sort
of speed and
efficiency.
Insertion-sort takes time ~ (seconds per say), where
k is constant
b) computer that B
does not depend
(much on nthan A)
slower
Merge-sort takes , where c is constant that does not
required to sort 10 million number
depend on n
using merge-sort
. Insertion-sort has a factor of n whereas merge-
sort: 
Insertion-sort run fast than merge-sort for small
value of n
05/07/2024 CENG 205 26
ALGORITHMS/DATA
STRUCTURES
Solution:
Efficiency – Insertion-sort and merge-
Let sort
A take instructions per second and B take
Algorithms
since differ from one another even though they
it is slower
solve the same problem in terms of speed and
efficiency.
Insertion-sort takes time ~ (seconds per say), where
k is constant that does not depend on n
Merge-sort takes , where c is constant that does not
depend on n
. Insertion-sort has a factor of n whereas merge-
sort: 
Insertion-sort run fast than merge-sort for small
value of n
05/07/2024 CENG 205 27
FLOWCHART SYMBOLS
Generally comprises of six basic
symbols

05/07/2024 CENG 205 28


FLOWCHART SYMBOLS
Generally comprises of six basic
symbols

Rules for creating flowchart


• All boxes are connected with arrows
• Decision symbol has two exit point
• Usually flow from top to bottom
• Subroutine have their own flowchart, etc
05/07/2024 CENG 205 29
FLOWCHART EXAMPLE
A flowchart (and equivalent Pseudocode) to compute the
interest on a loan

05/07/2024 CENG 205 30


FLOWCHART EXAMPLE
a flowchart and the equivalent Pseudocode is shown below. In this case, the
program computes the sum, average and product of three numbers:

Pseudocode

05/07/2024 CENG 205 31


FLOWCHART EXAMPLE
flowchart for a program that reads two numbers and displays the numbers
read in decreasing order

Pseudocode

05/07/2024 CENG 205 32


DECISION FLOWCHART

05/07/2024 CENG 205 33


DIRECTION OF NUMBERED
NYC STREETS ALGORITHM
Problem: Given a street number of a one-way street in New York
City, decide the direction of the street, either eastbound or westbound
Discussion: in New York City even numbered streets are Eastbound,
odd numbered streets are Westbound

34
FLOWCHART

35
LOOPING FLOW CHART

05/07/2024 CENG 205 36


FLOWCHART SYMBOLS
Example – Design an algorithm and
corresponding flowchart to add test score the
ff marks: 26, 49, 98, 87, 62, 75
1. Start 9. Get the 4th test score
2. Sum = 0 10. Add to sum
3. Get the 1st test score 11. Get the 5th test score
4. Add to first test score 12. Add to sum
to sum 13. Get the 6th test score
5. Get the 2nd test score 14. Add to sum
6. Add to sum 15. Output
7. Get the 3rd test score 16. Stop
8. Add to sum
05/07/2024 CENG 205 37
FLOWCHART SYMBOLS
Example –
Write an algorithm and draw the flowchart
for finding the average of two numbers, x
and y.

Write a C program to find the factorial value


of a number. Also write the algorithm and
draw flowchart

05/07/2024 CENG 205 38


FLOWCHART SYMBOLS
Self-check
Write an algorithm with flowchart to find the
area of a rectangle

a
05/07/2024 CENG 205 39
CLASS AVERAGE
ALGORITHM
Problem: Calculate and report the grade-point
average for a class
Discussion: The average grade equals the sum of
all grades divided by the number of students
Output: Average grade
Input: Student grades
Processing: Find the sum of the grades; count the
number of students; calculate average

40
Determine the average grade of a class.
Pseudocode:
Initialize Counter and Sum to 0
Do While there are more data
Get the next Grade
Add the Grade to the Sum
Increment the Counter
Loop
Computer Average = Sum / Counter
Display Average
05/07/2024 CENG 205 41
FLOWCHART

Pseudocode:
Initialize Counter and Sum to 0
Do While there are more data
Get the next Grade
Add the Grade to the Sum
Increment the Counter
Loop
Computer Average = Sum / Counter
Display Average

42
SELF CHECK
Write an algorithm and draw a flowchart that will
calculate the roots of a quadratic equation
ax  bx  c  0
2

Hint: , and the roots are:

and

Provide pseudocode as well


EXAMPLE
Write algorithm and draw a flowchart to
a) read an employee name (NAME), overtime hours worked (OVERTIME),
hours absent (ABSENT) and
b) determine the bonus payment (PAYMENT).
SOLUTION
Bonus Schedule
OVERTIME – (2/3)*ABSENT Bonus Paid

>40 hours $50


>30 but  40 hours $40
>20 but  30 hours $30
>10 but  20 hours $20
 10 hours $10
SOLUTION CONTINUES
Algorithm

Step 1: Start
Step 2: Input NAME, OVERTIME, ABSENT
Step 3: if (OVERTIME–(2/3)*ABSENT > 40) then
PAYMENT  50
else if (OVERTIME–(2/3)*ABSENT > 30) then
PAYMENT  40
else if (OVERTIME–(2/3)*ABSENT > 20) then
PAYMENT  30
else if (OVERTIME–(2/3)*ABSENT > 10) then
PAYMENT 20
else
PAYMENT  10
endif
Step 4: Print “Bonus for”, NAME “is $”, PAYMENT
Step 5: End
SELF CHECK
Flowchart: Draw the flowchart of the above algorithm?
ADVANTAGES OF USING
FLOWCHART
 Communication: Flowcharts are better way of communicating
the logic of a system to all concerned.
 Effective analysis: With the help of flowchart, problem can be
analysed in more effective way.
 Proper documentation: Program flowcharts serve as a good
program documentation, which is needed for various purposes.
 Efficient Coding: The flowcharts act as a guide or
blueprint during the systems analysis and program development
phase.
 Proper Debugging: The flowchart helps in debugging process.
 Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part.
05/07/2024 CENG 205 48
LIMITATION OF
FLOWCHART
Complex logic: Sometimes, the program logic
is quite complicated. In that case, flowchart
becomes complex and clumsy.
Alterations and Modifications: If alterations are
required the flowchart may require re-drawing
completely.
Reproduction: As the flowchart symbols cannot
be typed, reproduction of flowchart becomes a
problem.
The essentials of what is done can easily be lost in
the technical details of how it is done.
05/07/2024 CENG 205 49
The syntax of C pretty-well guarantees you will easily understand
other languages that came afterwards like C++, Java, Javascript,
and C#.NET
05/07/2024 CENG 205 50
COURTESY OF
CONFUCIUS
Learning by doing is probably the
most effective way to maximize
retention.

I hear and I forget


I see and I remember
I do and I understand
 51
TODAY – LECTURE SET
OVERVIEW
Components of a computer program (in C)
Simple data types
Arithmetic expressions and precedence rules
The printf function

http://www.tutorialspoint.com/
cprogramming/index.htm

05/07/2024 CENG 205 52


STATEMENT
STRUCTURES
Sequence – follow instructions from one line to the
next without skipping over any lines
Decision - if the answer to a question is “Yes” then
one group of instructions is executed. If the answer
is “No,” then another is executed
Looping – a series of instructions are executed over
and over

53
PROGRAMMING LANGUAGE CLASSIFICATION
High-level languages: Closer to human
language, E.g. C, C++, Java, Visual Basic
Easier to intuitively program
Not CPU specific, portable with the right compiler
More than 1,000 available
Assembly languages: Closer to what
the computer processes
CPU specific, faster than high-level languages
More tedious to program
Machine language: The sequence of 0 and
1 processed by the CPU
05/07/2024 CENG 205 54
HUMAN VS. PROGRAMMING LANGUAGES
Human Languages Programming Languages
Learn grammar rules, E.g.,
Learn grammar rules, E.g., The printf(“Hello World\
book has arrived” vs. “Book n”); vs.
arriving has” printf(Hello world)
Learn to compose meaningful Learn to compose meaningful
sentences E.g., “The table is sentences x = 0; y =
having a fever”  Syntactically 10/x;
correct but not meaningful
Learn how to use
Learn how to use words/functions
words/sentences programs/applications in a
paragraphs/chapters in a concise and functional way
concise and functional way
Difference: No flexibility
Difference: Flexibility in
expression
05/07/2024 CENG 205 55
PROCESS FOR BUILDING AND EXECUTING A PROGRAM

Compil
Edit Link Load Execute
e

Write program in a text editor


Translate program in machine code, create object files
Resolve cross-references among object files and link
them into one executable
Load executable file into memory and initiate execution
File is executed and results are stored/displayed
05/07/2024 CENG 205 56
HIGH-LEVEL LANG.
PROGRAM DEV. CYCLE

 The process of program compilation, linking, and execution


 Even when a program executes without an error message, the
results must be checked carefully to be sure that they are correct.
 The computer performs the steps precisely as specified in the
source; if the wrong steps are specified, the computer will execute
these wrong (but syntactically correct) steps and produce a result
that is incorrect
Garbage in ; Garbage out  57
BEFORE YOU START TYPING – SOFTWARE
DEVELOPMENT

Specify problem requirements: understand what you are


asked
Analyze the problem: Inputs, outputs, constraints, test cases
Design the algorithm: How do you obtain the output, given
input and constraints
Implement the algorithm: Convert the algorithm to
statements of the programming language
Debug the program: Correct syntax and conceptual errors
Test the program: Define possible test cases for verification
of correct operation
05/07/2024 CENG 205 58
BEFORE YOU START TYPING – SOFTWARE
DEVELOPMENT

Text Editor – for typing the source code


C Compiler - The source code written in source file is the
human readable source for your program. It needs to be
"compiled", i.e. to turn into machine language so that your
computer can actually execute instructions in the program as
directed by your code.

05/07/2024 CENG 205 59


EXAMPLE: CONVERTING FAHRENHEIT TO CELSIUS

You have a summer travel to Europe and need to write a


program that converts Fahrenheit degrees to Celsius degrees
for your trip.
Specify problem requirements: Convert Fahrenheit to Celsius
Analyze the problem:
Input: Fahrenheit (what format?)
Output: Celsius (what format?),
Constraints? Absolute zero: −459.67° F
Test cases: 0° F, -500° F, 1,000,000,000° F, -459.67° F, -32° F, a, ~
Design the algorithm: C = 5* (F – 32)/9
Implement the algorithm: We will see how!
Test the program: Input test values
05/07/2024 CENG 205 60
COMPONENTS OF A
PROGRAM
Instructions to
the compiler

Data structures to
hold data

Instructions for
manipulating the
data

05/07/2024 CENG 205 61


Rom. 12:2
Do not conform to the pattern of this world, but be transformed by
the renewing of your mind. Then you will be able to test and
approve what God's will is – his good, pleasing and perfect will.
05/07/2024 CENG 205 62
HIGH-LEVEL LANG.
PROGRAM DEV. CYCLE

 The process of program compilation, linking, and execution


 Even when a program executes without an error message, the
results must be checked carefully to be sure that they are correct.
 The computer performs the steps precisely as specified in the
source; if the wrong steps are specified, the computer will execute
these wrong (but syntactically correct) steps and produce a result
that is incorrect
Garbage in ; Garbage out  63
BEST WAY TO LEARN PROGRAMMING

Write programs – The first C program


A simple C program
#include<stdio.h>

int main(void)
{
printf(“Hello Class, this is my first C program\n”);
return(0);
}

Output: Hello Class, this is my first C program


05/07/2024 CENG 205 64
RE-EXAMINING A C PROGRAM

A C program basically consists of the


following parts:
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
A simple C “Hello
World” Program
RE-EXAMINING A C PROGRAM
pre-processor directive #include<stdio.h>
main function int main(void)
beginning of function
{
function from library printf(“My first C program\n”);
returned value (output) return(0);
end of function
}
Argument
Same structure regardless of the complexity of a program
Pre-processor declarations
Main function
Begin
Data structures
Control structures
Call of other functions (either user-
created or called from libraries)
End
05/07/2024 CENG 205 66
05/07/2024 CENG 205 67
C BASIC SYNTAX
 A C program consists of various tokens and a token is either a
keyword, an identifier, a constant, a string literal, or a symbol.
 For example, the following C statement consists of five tokens
 printf("Hello, World! \n");

 Semicolons ; – statement terminator. It indicates the end of one


logical entity.
 Identifiers
 A C identifier is a name used to identify a variable, function, or any other user-
defined item.
 An identifier starts with a letter A to Z or a to z or an underscore _ followed by
zero or more letters, underscores, and digits (0 to 9).
 Keywords are reserved words

05/07/2024 CENG 205 68


DATA STRUCTURES – SIMPLE DATA TYPES
A variable/identifier is a location in your
computer's memory in which you can store
a value.
Data Type: Tells the compiler the kind of
variable we are defining. E.g. an integer, a
character, etc.
The type of the variable amount of
memory to set aside.
signed and unsigned indicate positive or
negative integers
05/07/2024 CENG 205 69
GENERAL DATA TYPES
Types Description
Basic They are arithmetic types and consists of the two
types: (a) integer types and (b) floating-point types.
Enumerated They are again arithmetic types and they are used to
define variables that can only be assigned certain
discrete integer values throughout the program.
The type void The type specifier void indicates that no value is
available.
Derived types They include (a) Pointer types, (b) Array types, (c)
Structure types, (d) Union types and (e) Function
types.

05/07/2024 CENG 205 70


BASIC/SIMPLE DATA TYPES IN C
int days;
int: integers numbers or days = 7;
quantity
float miles;
float: single precision miles = 1.609;
floating-point numbers
double mem;
double: double precision mem = 2600000;
floating-point numbers
char letter;
char: defines characters letter = ‘A’;

void: represents absence


of a type
05/07/2024 CENG 205 71
RANGE AND MEMORY ALLOCATION FOR DATA TYPES
Data Type Bytes Bits Range
short int 2 16 -215 to 215-1
unsigned short int 2 16 0 to 216-1
unsigned int 4 32 0 to 232-1
int 4 32 -231 to 231-1
char 1 8 -27 to 27-1 or 0 to 28-1
signed char 1 8 -27 to 27-1
unsigned char 1 8 0 to 28-1
float 4 32 -231 to 231-1
double 8 64 -263 to 263-1
long double 12 96 -295 to 295-1

Note: The number of bits allocated per data type is language/OS/CPU


dependent
05/07/2024 CENG 205 72
VARIABLES CREATION
 A variable definition  tells the compiler where and how
much space is required the variable.
datatype var1 = value1, var2 = value2, … ;
 A variable declaration specifies a data type and contains a
list of one or more variables of same data type separated by
a comma as follows:
dataType variable1, variable2, ….;
 A variable declaration provides assurance to the compiler
that there is one variable existing with the given data type
and name
 It has meaning only at the time of compilation, compiler
needs actual variable declaration at the time of linking of
the program.
05/07/2024 CENG 205 73
VARIABLES CREATION
Rules on naming your variables
A variable must consist only of letters, digits, and
underscores
A name cannot begin with a digit
A C reserved word cannot be used as a name
Examples of valid names
letter_1, My_First_Initial, Hello,
KMS_PER_MILE, myAge, my_Car, myCar,
etc
Example of invalid names
1letter, double, int, two*four,
joe’s, [TK Samuel]
05/07/2024 CENG 205 74
VARIABLES CREATION
Dealing with constants
Constant cannot contain blank space or
commas
Can be preceded by a minus (-)sign
No semicolon (;) at end
#define FIXBREADTH value
#define MAXLINE 1000
const dataType myFixNumber = value;
const double extra = 2.71828185905;
05/07/2024 CENG 205 75
VARIABLE CREATION
To declare a variable:
Syntax: data_type var_name1, var_name2,
var_name3
Example: int fahr, celsius;
double x, y, z;
char my_name, answer;
char text[5] = “Ghana”;
C complier uses declarations to allocate
memory space for data
05/07/2024 CENG 205 76
VARIABLE
INITIALIZATION
dataType variable_name = value;
int d = 3, f = 5; // definition and
initializing d and f.
byte z = 22; // definition and initializes
z.
char x = 'x'; // the variable x has the
value 'x'.

05/07/2024 CENG 205 77


STATEMENTS AND
EXPRESSIONS
Variable initialization Syntax: variable = value;
Examples
days = 7;
letter1 = ‘A’;
lower = 0;
Assignment statements
A statement causes the computer to carry out
some action.
Types of statements in C
Expression statements, compound
statements and control statements.
05/07/2024 CENG 205 78
STATEMENTS AND
EXPRESSIONS
Variable initialization Syntax:
Examples
variable = value;
days = 7;
letter1 = ‘A’;
Assignment statements lower = 0;

Syntax: variable = expression;


Examples
fahr = lower; Assignment operator
celsius = 5*(fahr-32)/9;
sum = x + y + z;

Be careful: You have to declare your variables before


you can use them. All variables on the right side must
be initialized
05/07/2024 CENG 205 79
EXAMINING A
PROGRAMME
Main function definition

05/07/2024 CENG 205 80


INSERTING COMMENTS INTO YOUR CODE
Writing comments in your code is very crucial for
readability purposes
Common problems if you do not write comments
Anyone else who reads your code cannot understand it. Hence
he/she cannot help you
You cannot understand your own code a week after you wrote it.
Comments in C: Can be inserted anywhere in the
/* Owner: Loukas Lazos*/

program // Standard input/output library


#include<stdio.h>

Syntax: /* anything you want */


// main function
int main(void)
{ or // for a single line comment
printf(“My first C program\n”); // print statement
return(0);
}
05/07/2024 CENG 205 81
PRE-PROCESSOR DIRECTIVES

#include
Gives the program access to header files of standard
libraries
Example standard library header files: stdio.h,
math.h, string.h, etc.
Gives the program access to user-defined libraries as
well#include <header_file.h> /* for standard
Syntax:
A library
libraries */ is a collection of object files that
perform certain functions
#include “user_file.h” /* for user-defined
Sometimes
libraries */ explicit linking may be needed (e.g.,
math.h)
Example: #include <stdio.h> /* Most programs include
this */
05/07/2024 CENG 205 82
DATA STRUCTURES -
CONSTANTS
Many times a specific value is used multiple times throughout
the program
Can be pre-defined in a macro
syntax: #define macro_name value

#define PI 3.14159 /* Symbolic constant */

angle = 2*PI; /* PI is substituted with the


3.14159 value */
By convention symbolic constants are uppercase
NOTE: no semicolon at the end of the declaration

05/07/2024 CENG 205 83


RESERVED WORDS – NAMES TO AVOID

ANSI C list of reserved words


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Reserved words may not be used to name variables


05/07/2024 CENG 205 84
DECLARATION AND INITIALIZATION

int days; 4 bytes


? 7
days = 7;

float miles; 4 bytes


miles = 1.609; ? 1.609

double mem; 8 bytes


mem = 2600000; ? 2600000

The amount of memory allocated per data type is


machine/OS dependent
05/07/2024 CENG 205 85
DATA TYPE MODIFIERS
There are additional modifiers that can be used
with data types to manipulate the memory
allocation
Modifiers E.g.
Short short int days;
long long int counter;
unsigned long double nanometers;
signed

05/07/2024 CENG 205 86


WHAT WE’VE LEARNT SO
FAR!
 History and components of Computer
 History of computer programming and importance of
computer software
 Available careers and market places
 Interaction between software and hardware
 Algorithm and flow chart creation
 Software development procedure
 Application of computer programming in field of study
 Basic C syntax and jargons – Fundamentals
 Data type
 Outputting functions
 Keywords
 Identifiers/Variable creation
05/07/2024 CENG 205 87
 Constants
RULES FOR EVALUATING EXPRESSIONS

Operator Precedence Group

05/07/2024 CENG 205 88


ARITHMETIC OPERATORS
Operator Description Example

+ Adds two operands A + B will give 30


You
- can manipulate
Subtracts second operand int, float
from A - and
B willdouble
give -10
data
the first
* Multiples both operands A * B will give 200
/ Divides numerator by de- B / A will give 2
numerator
% Modulus Operator and remainder B % A will give 0
of after an integer division
++ Increments operator increases A++ will give 11
integer value by one
-- Decrements operator decreases A-- will give 9
integer value by one
A = 10,
05/07/2024 CENG 205
B89 = 20
RULES FOR EVALUATING EXPRESSIONS
Parentheses rule
All expressions in parentheses must be evaluated
separately
Nested parenthesized expressions must be evaluated
inside out (40+9)/(3+(3+1)) = 7

Operator precedence rule


First: Unary + , - BODMAS?
Next: *, /, %
Last: binary +, -
Associativity rule
Unary operators in the same precedence level: right to left
z*y*x
Binary operators in – precedence
the same a/b +c*d = left to right
level:
(z*y*x)-(a/b)+ (c*d)
05/07/2024 CENG 205 90
RELATIONAL OPERATORS
Op. Description Example
== Checks if the values of two operands (A == B) is not
are equal or not, if yes then condition true.
becomes true.
!= Checks if the values of two operands (A != B) is
are equal or not, if values are not true.
equal then condition becomes true.
> Checks if the value of left operand is (A > B) is not
greater than the value of right true.
operand, if yes then condition
becomes true.

A = 10,
05/07/2024 CENG 205
B91 = 20
RELATIONAL OPERATORS CONT’D

Op. Description Example


< Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if
yes then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not
greater than or equal to the value of true.
right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is (A <= B) is
less than or equal to the value of right true.
operand, if yes then condition
becomes true.
A = 10,
05/07/2024 CENG 205
B92 = 20
TYPICAL C PROGRAM

Output:
value of c : 30 declaration

value of f :
23.333334
Extern variable is a
global variable
accessible to a
function below it
05/07/2024 CENG 205 93
DISPLAYING OUTPUT
Output operation: data displayed on a screen or stored on/in a file
Syntax: printf(“format string”, variable list);
Examples
printf(“%d\t%d\n”, x, y);
printf(“%3d %6d\n”, x, y);
printf(“%.0f %6.1f\n”, x, y);

Argumen Operation
t
%d print as a decimal number
%3d print as a decimal number in three digit format
%6.1f print as a floating point number with six digits
(including decimal point) and one decimal digit
%.2f print as a floating point number with two decimal
digits
%c
05/07/2024 print as a character CENG 205 94
DISPLAYING OUTPUT
Output operation: data displayed on a screen or stored on/in a file

05/07/2024 CENG 205 95


ESCAPE CHARACTERS IN C
Escape Description
character
\t Horizontal tab
\v Vertical tab
\n New line
\b Back space
\r Carriage return
\f New page
\a Bell
\0 void (end of a string)
\’ Signe quote
\” Double quote
\\ Backslash
\? Question mark

05/07/2024 CENG 205 96


PRINTING OR DISPLAY EXAMPLE EXAMPLE

#include<stdio.h>
// Example of printing variables with the printf
function

int main(void)
{
int x; // declaration of an integer
float y; // declaration of a float
char c;

x = 125; // initialization
y = 3.14159; // initialization
c = 'a'; // initialization
05/07/2024 CENG 205 98
PRINTING EXAMPLE – CONT’D
printf("Printing an integer number:%d\n", x); //
integer
printf("Printing a float number:%f\n",y); // real
printf("Printing a character:%c\n",c); // char
printf("You can also print message prompts\n");
printf("Integer:%d\tFloat:%.1f\n",x,y); // printing
tabs
printf("Two decimals:%4.2f\nThree decimals:
%6.3f\n",y,y);
// decimals
return(0);
}

05/07/2024 CENG 205 99


TILL NEXT MEETING …

I have
questions…

05/07/2024
! CENG 205 101

You might also like