0% found this document useful (0 votes)
38 views42 pages

DFC 10042problem Solving & Problem Design: Chapter 4: Basic Programming Codes

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 42

DFC 10042PROBLEM SOLVING

& PROBLEM DESIGN


1

CHAPTER 4: BASIC PROGRAMMING


CODES
AT THE END OF THIS CHAPTER,
STUDENTS SHOULD BE ABLE TO:
2

1. UNDERSTANDING BASIC PROGRAMMING CODES


Identify elements of the programming language:
a) Comment
b) Pre-processor directive
c) Standard header file
d) Main function
e) Reserved word (standard and user-defined identifiers)
f) Identifiers (constants and variable)
g) Special symbol
h) Punctuation
i) Statements
j) Blocks
a) comment
3

What is a comment ?
 a comment is a programming language construct used
to embed programmer-readable annotations in
the source code of a computer program.
 Those annotations are potentially significant to
programmers but typically ignorable
to compilers and interpreters.
 Comments are usually added with the purpose of
making the source code easier to understand. The
syntax and rules for comments vary and are usually
defined in a programming language specification.
a) comment
4

What is a comment ?

An illustration
of Java source
code with prologue
comments indicated
in red and inline 
comments in green.
Program code is
in blue.
b) Preprocessor directive
5

What’s a #?
 Any line that begins with # symbol is a pre-processor
directive
 Processed by preprocessor before compiling
What’s pre-processor?
 A utility program, which processes special instructions
are written in a C/C++ program.
 Include a library or some special instructions to the
compiler about some certain terms used in the program
 Different preprocessor directives (commands) perform
different tasks.
 It is a message directly to the compiler.
b) Preprocessor directive
6

 How to write/syntax ?
 Begin with #
 No semicolon (;) is expected at the end of a preprocessor
directive.
 Example : #include and #define

Preprocessor
Directives
b) Preprocessor directive
7

Example:
pre-processor Meaning
directive
#include <FILE> Include a header file
#include <iostream> Tells preprocessor to include
the input/output stream
header file <iostream>

#define NAME “boB” Define a constant


#ifdef Conditional compilation…
#endif
b) Preprocessor directive
8

The #define Preprocessor Directive:


 Symbolic constants
 Constants represented as symbols
 When program compiled, all occurrences replaced
 Format
 #define identifier replacement-text
 #define PI 3.14159
 Everything to right of identifier replaces text
 #define PI=3.14159
 Replaces PI with "=3.14159"
 Probably an error
 Cannot redefine symbolic constants
b) Preprocessor directive
9

The #define Preprocessor Directive:


 Advantage:
 Takes no memory
 Disadvantages:
 Name not be seen by debugger (only replacement
text)
 Do not have specific data type
 const variables preferred
c) Standard Header file
10

Standard header file, sometimes known as an include


file. Header files almost always have a .h extension.
Why use header file?
 For big projects having all the code in one file is
impractical. But if we split the project into smaller
files, how can we share functions between them? Ans:
By using Headers!
 The purpose of a header file?
 To hold declarations for other files to use.
 When we use the line #include <iostream>, we
are telling the compiler to locate and then read all the
declarations from a header file named “iostream”.
c) Standard Header file
11

 Bear in mind that header files typically only contain


declarations.
 They do not define how something is implemented.
 Consider the following program:

This
program
prints
“Hello,
world!”
using cout.
c) Standard Header file
12

o In program never defines cout, so how does the compiler


know what cout is?
o The answer is that cout has been declared in a header file
called “iostream”.

o If cout is only defined in the “iostream” header file,


where is it actually implemented?
o Answer: It is implemented in the runtime support library,
which is automatically linked into your program during
the link phase.
d) Function main
13

 Function main is a part of every C++ program and identify


the start of the program
 Exactly one function in a program must be main
 main is a Keyword.
 Keyword : A word in code that is reserved by C++ for a
specific use.
 Header of function main?:
 int main( )
d) Function main
14

The structure of a main Function:


An empty
argument
list
Function
name

Type of
return value int main ( )
{
Function C++ Program statements in here;
body Return 0;
}
d) Function main
15

4 common ways of main declaration

int main(void)
{
void main(void)

return 0; { main(void)
}
{ main( )
}
{
}

}
e) Reserved Word/Keywords
16

Keywords (also called reserved words)


 Reserved words in the C++ language for specific use.
 Must be used as they are defined in the programming
language
 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)
 Should be typed in lowercase.
 Example: const, double, int, main, void,printf,
while, for, else (etc..)
e) Reserved Word/Keywords
17

Cannot be used as identifiers or variable names


f) Identifiers (Constant & Variable)
18

Is a word used to represent certain program


entities (variables, function names, constant,etc).
Example:
 int my_name;
 my_name is an identifier used as a program variable
 void CalculateTotal(int value)
 CalculateTotal is an identifier used as a function name

F2037 Programming Fundamentals with C++


f) Identifiers (Constant & Variable)
19

 Identifiers as Constant
 Entities that appear in the program code as fixed values.
 Any attempt to modify a CONSTANT will result in error.

 Declared using the const qualifier


 Also called named constants or read-only variables
 Must be initialized with a constant expression when
they are declared and cannot be modified thereafter
 Example: const int size = 5;
f) Identifiers (Constant & Variable)
20

 Identifiers as Variable is a location in memory which:


 we can refer to by an identifier, and
 in which a data value that can be change
 Where value can be stored
 Common data types (fundamental, primitive or built-in)
 int – integer numbers : 1, 2, 4,….
 char – characters : ‘a’, ‘c’, …
 float, double: floating point numbers: 2.5, 4.96
 The value of a variable could be changed while the program is
running.
 Declaring a variable means specifying both its name and its
data type
f) Identifiers (Constant & Variable)
21

 Example of Variables:
i)int is an abbreviation for integer.
 Integer store value: 3, 102, 3211, -456, etc.
 Example variable : number_of_bars

ii)double represents numbers with a fractional


component
 double store value: 1.34, 4.0, -345.6, etc.
 Example variable : one_weight ,total_weight
f) Identifiers (Constant & Variable)
22

 Naming convention rules for identifier:


 They are formed by combining letters, digits & underscores.
 Blank space is not allowed in an identifier.
 The first character of an identifier must be a letter.

valid invalid reason


Monthly_Salary Monthly Salary Blank space cannot
be used
Month1 1stMonth Digit cannot be used
as a first character
Email_add email@ Special characters
cannot be used
g) Special symbol
23

symbol name symbol sign Meaning/ uses


Pound # Used for preprocessor directives

Double Slash // single line style comment used in C++


programs only
double quotes ““ •Enclose a string is a sequence of
characters.
•To begin and end a string
constant/string literal
single quotation ‘ ‘ To begin an end a character constant/
mark character literal

Newline \n
Horizontal tab \t
h) Punctuation
24

 Punctuation is used in programming languages, as it is


in natural languages. 
 The punctuation marks listed here have syntactic
meaning to the compiler. 
 Operators are listed separately.
 The following table show the basic Punctuation in C++
Programming:
h) Punctuation
25

Punctuation Punctuation Meaning/ uses


name sign
semicolon ; End of statement or to terminate an
expression/ statement.
colon : • to terminate a statement label.
• Used for case labels;
• used in the conditional operator;
Parentheses () to group parts of an expression, and
as syntactic elements in if and while
statements.  Parentheses should
always be used in matched pairs.
h) Punctuation
26

Punctuation Punctuation Meaning/ uses


name sign
Comma , - To separate multiple expressions
in a single statement;
- to declare several variables in a single
statement;
- to separate lists of parameters/
arguments in functions and function
calls
curly braces {} • to group a sequence of statements. 
•Braces should always be used in
matched pairs.
•Identify a segment / body of a program.
i) Statements
27

What is statement?
 A specification of an action to be taken by the computer as the program executes.
 Instruct the program to perform an action
 All statements end with a 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
Examples :
 return 0;

 cout << “Welcome to C++!\n ”;


j) Blocks
28

 Block is body statement between curly braces { }


 Identify a segment/ body of a program
 The start and end of a function
 The start and end of the selection or repetition block.
 Since the opening brace indicates the start of a segment
with the closing brace indicating the end of a segment,
there must be just as many opening braces as
closing braces.
 Many opening braces as closing braces in code (this
is a common mistake of beginners)
AT THE END OF THIS CHAPTER,
STUDENTS SHOULD BE ABLE TO:
29

1. UNDERSTANDING BASIC PROGRAMMING CODES


• Analyze a program to identify IPO
• Construct pseudo code and flowchart based on given
programming code
• Design a program from problem analysis, algorithm until
development of code statements
Analyze a program to identify input,
process and output
30

Pseudocode 1 C++ Program Code 1


#include <iostream>
START using namespace std;
void main()
Input num1, num2, num3; {
Total = num1 + num2 + num3; int num1, num2, num3, Total, Average;
cout<<“input num1, num2, num3”;
Average = (num1 + numr2 + cin>> num1, num2, num3;
num3)/3;
Total = num1 + num2 + num3;
Display Total, Average; Average = (num1+num2+num3)/3;

END cout<<Total;
cout<< Average;
}
Identify input, process and output from Programming Code 1
31

#include <iostream>
using namespace std;
void main( )
{
int num1, num2, num3;
cout<<“input num1, num2, num3”;
INPUT
cin>> num1, num2, num3;

Total = num1 + num2 + num3;


Average = (num1+num2+num3)/3;
PROCESS
cout<< Total;
cout<< Average; OUTPUT
}
Identify input, process and output from Programming Code 2
32

Pseudocode 2 C++ Program Code 2

#include <iostream>
Start using namespace std; INPUT =
void main() none
set Package = 699; {
Discount = 15/100 * Package; float package, discount, NewPrice;
NewPrice = Package –Discount; Package = 699.00;
Print NewPrice; Discount = 15/100 * Package;
NewPrice = Package –Discount;
End
cout>> NewPrice ; PROCESS
}
OUTPUT
Convert Pseudocode to Programming Code
33

Pseudocode 3 C++ Program Code 3


Start #include <iostream>
using namespace std;
Input height , weight
void main()
BMI = weight / (height * height) { float height , weight, IBM;
cout<<“input height , weight”;
cin>> height , weight;
if (BMI <18)
Print “under weight” BMI = weight / (height * height);
else if ((BMI >= 18) && (BMI <= 24)) if (BMI <18){
Print “ ideal weight” cout<< “under weight”;
else if ((BMI > 24) && (BMI <= 30)) elseif ((BMI >= 18) && (BMI <= 24))
cout<<“ ideal weight”;
Print “overweight”
elseif ((BMI > 24) && (BMI <= 30))
else cout<< “overweight”;
Print “obese” else
cout<< “obese”; }
End }
Identify input, process and output from Programming Code 3
#include <iostream> 34

using namespace std;


void main()
{ float height , weight, BMI;
cout<<“input height , weight”; INPUT
cin>> height , weight;
BMI = weight / (height * height);
if (BMI <18){
cout<< “under weight”;
PROCESS
elseif ((BMI >= 18) && (BMI <= 24))
cout<<“ ideal weight”;
elseif ((BMI > 24) && (BMI <= 30)) OUTPUT –
based on
cout<< “overweight”; Result of
else the user
cout<< “obese”; } condition
}
Convert Pseudocode to Programming Code
35

Pseudocode 4 C++ Program Code 4


#include <iostream>
Start
using namespace std;
sum = 0, i = 1 void main()
{
while (i<= 6) int number, sum = 0, i = 1;
{
while (i<= 6)
input the number {
sum= sum + number cout << "input 1 number: ";
cin>> number;
i = i +1 sum = sum + number;
} i = i +1;
}
Print sum cout<< "sum of 6 numbers="<< sum ;
End }
Identify input, process and output from Programming Code 4
#include <iostream> 36
using namespace std;
void main()
{ int number, sum, i; INPUT

sum = 0, i = 1;
while (i<= 6)
{ cout << "input 1 number: ";
cin>> number; PROCESS

sum= sum + number;


i = i +1;
}
cout<< "sum of 6 numbers="<< sum ; OUTPUT

}
DISCUSSION
37
#include <iostream>
using namespace std; Question:
void main() Based on program
{ int number, sum, i , average; code given, identify
sum = 0, i = 1; input, output and
process of the
For (i = 1; i<= 20; i++)
program
{ cout << "input weight: ";
cin>> number;
sum = sum + weight;
}
average = sum/20
cout<< " Average of 20 weight="<< average ;
}
Construct pseudo code and flowchart based on given programming
code.
38

Programming code Pseudocode


#include <iostream>
Start:
using namespace std;
void main() i=1, sum=0
{ Do
int i , sum, weight, average ; {
i=1, sum=0;
input weight
Do
{ cin>> weight; sum = sum + weight
sum = sum + weight; i++;
i++; } while (i <= 20)
} while (i <= 20) average = sum/20
average = sum/20
cout<<average; Print average
} End:
Construct pseudo code and flowchart based on given programming
code.
39
start

i= 1, sum=0

Input weight

Sum+= weight

i ++

Average=Sum/20
i <= 20
false
true Print Average

end
Instruction: Develope pseudo code and flowchart based on programming code given .
40

Program code A Program code B


(using While Loop) (using For Loop)
#include <iostream> #include <iostream>
using namespace std; using namespace std;
void main( ) void main( )
{ int i=1, sum=0, average; { int i=1, sum=0, average;
while (i<= 20)
for (i = 1; i<= 20; i++)
{
{
cin>> weight;
cin>> weight;
sum = sum + weight;
i++;
sum = sum + weight;
} }
average = sum/20; average = sum/20;
cout<< average; cout<< average;
} }
Design a program using a given problem from problem
analysis, algorithm until development of code statements.
41

 Activity Outcome: Write the problem analysis,


algorithm, pseudo code, flow chart and coding to
compute the total overtime wages of an employee using
sequence control structure.
 
As a programmer, you need to develop a system to
compute the total overtime wages of an
employee and print the result. Write the
problem analysis, algorithm, pseudo code, flow
chart and coding for that problem using sequence
control structure.
FINISHED SYLLABUS FOR
DFC10042!
42

GOOD LUCK FOR YOUR FINAL EXAM

YOU CAN GET ‘A’


IF YOU DO AS ‘A’ !

You might also like