You are on page 1of 39

PLT 101 Computer Programming

CHAPTER 1
INTRODUCTION TO COMPUTER
PROGRAMMING
(Part 2)
Lecturer: Mrs Nurul Izni Rusli
nurulizni@unimap.edu.my
UNICITI S2 BK5 Level 1

Outline
Pseudo code & flowchart
Sample programming question
Sample C program

Identifiers and reserved words


Program comments
Pre-processor directives
Data types and type declarations
Operators

Formatted input and output


2

Program debugging

Sample C Programming Question 1


Write a program that calculates area of

triangle.
Your program should read the base length and the
height length from user. Given the formula to
calculate the area of triangle: 0.5 x (base) x (height).

Steps:
Analyze the problem

Use algorithm
Convert to actual codes

Sample C Programming Question 2


Write a program that calculates area of circle. Your

program should read the radius from user. Given the


formula to calculate the area of circle: 3.14 x (radius)
x (radius).
Steps:
Analyze the problem

Use algorithm
Convert to actual codes

Recall..Pseudo Code and Flowchart


Try develop the pseudo code and flowchart for the
problem given in the previous slide.

Sample C Program - Question 1


//Program name : program1.c
//Programmer :Yasmin
//This program calculates the area of triangle
#include <stdio.h>
Preprocessor

begin

int main(void)
{
double base, height, area;

Variables
declaration

printf(Enter base length : );


scanf(%f , &base);
printf(Enter height length : );
scanf(%f , &height);
area=0.5 * base * height;
printf(\nArea of the triangle is : %5.2f\n, area);
return 0;
}

end
6

return 0 (int) to
OS

Comments
directives

The term void indicates we receive


nothing from OS and return an
integer to OS
body

Sample C Program - Question 2


//This program calculates the area of triangle
#include <stdio.h>

int main ()
{
double r, area;
printf("Enter radius : ");
scanf("%lf", &r);
area=3.14*r*r;
printf("\nArea of the circle is : %lf\n", area);
return 0;
}

Variables and Reserved Words


Identifiers/Variables
labels for program elements
case sensitive
can consist of capital letters[A..Z], small letters[a..z],

digit[0..9], and underscore character _


first character MUST be a letter or an underscore
no blanks
reserved words cannot be variables/identifiers
Reserved words
already assigned to a pre-defined meaning
e.g.: delete, int, main, include, double, for, if, etc.

Program Comments
Starts with /* and terminates with */ OR
Character // starts a line comment, if several lines,

each line must begin with //


Comments cannot be nested /* /* */*/

Preprocessor Directives
An instruction to pre-processor
Standard library header: <stdio.h>,<math.h>
E.g.
o #include <stdio.h>
for std input/output
o #include <stdlib.h>
conversion number-text vise-versa, memory

allocation, random numbers


o #include <string.h>
string processing
10

Data Types and Memory Allocation


Data Type

Size
(bytes)

A single character. Internally stored as a coded


integer value (refer to ASCII table).

Integer quantity. Can be represented in signed or


unsigned form (with the unsigned keyword).

Floating-point number. Set of real numbers.

double

A more precise version of float. Has larger dynamic


range and better representation of decimal points.

bool

Boolean representation of logic states. Can only be


assigned true (1) or false (0).

char
int

float

11

Description

Data Types Declaration


float income;

float income, net_income;

float net_income;
double base, height, area; Declare and initialize
int index =0, count =0;
char ch=a, ch2;
const float epf = 0.1, tax = 0.05;
Named constant declared and initialized

12

Types of Operators
Types of operators are:
Arithmetic operators
(+ , - , * , / , %)
Relational operators
(> , < , == , >= , <=, !=)
Logical operators (&& , ||)
Compound assignment operators
(+=, -=, *=, /=, %=)
Binary operators: needs two operands
Unary operators: single operand

Bitwise operators: executes on bit level

13

Arithmetic Operators
Used to execute mathematical equations
The result is usually assigned to a data storage

(instance/variable) using assignment operator ( = )


E.g.
sum = marks1 + marks2;

14

Arithmetic Operators cont.


C Operation

Algebraic
Expression

C Expression

f+7

f+7

pc

p-c

Multipication

bm

b*m

Division

x/y

Addition
Subtraction

Remainder
(Modulus)
15

Arithmetic
Operator

r mod s

x/y

r%s

Arithmetic Operators cont.


Exercise
Given x = 20, y = 3

z=x%y
= 20 % 3
= 2 (remainder)

16

Relational and Logical Operators

Previously, relational operator:

>, < >=, <=, == , !=


Previously, logical operator:
&&, ||
Used to control the flow of a program
Usually used as conditions in loops and branches

17

More on Relational Operators


Relational operators use mathematical comparison

(operation) on two data, but give logical output


e.g.1 let say b = 8, if (b > 10)
e.g.2 while (b != 10)
e.g.3 if (mark == 60) print (Pass);
Reminder:
DO NOT confuse == (relational operator)
with = (assignment operator)

18

More on Logical Operators

Logical operators are manipulation of logic. For

example:
i. b=8, c=10,
if ((b > 10) && (c<10))
ii. while ((b==8) || (c > 10))
iii. if ((kod == 1) && (salary > 2213))

19

Truth Table for && (Logical AND) Operator

20

exp1

exp2

exp1 && exp2

false

false

false

false

true

false

true

false

false

true

true

true

Truth Table for || (Logical OR) Operator

21

exp1

exp2

exp1 || exp2

false

false

false

false

true

true

true

false

true

true

true

true

Compound Assignment Operators


To calculate value from expression and store it in

variable, we use assignment operator (=)


Compound assignment operator combines binary

operator with assignment operator


o E.g. val +=one; is equivalent to val = val + one;
o E.g. count = count -1; is equivalent to

count -=1;
count--;
--count;

22

Unary Operators
Obviously operating on ONE operand
Commonly used unary operators
Increment/decrement { ++ , -- }
Arithmetic Negation { - }
Logical Negation { ! }

Usually using prefix notation


Increment/decrement can be both a prefix and

postfix
23

Comparison of Prefix and Postfix


Increments

24

Unary Operators
Example
Increment/decrement { ++ , -- }
prefix:value incr/decr before used in expression
postfix:value incr/decr after used in expression
val=5;

Output:

val=5;

Output:

printf (%d, ++val);

printf (%d, --val);

val=5;

Output:

val=5;

Output:

printf (%d, val++);

printf (%d, val--);

Logical Negation { ! }
bool isDinnerTime = true;
bool isLunchTime = !isDinnerTime;

25

Operator Precedence

26

Operators

Precedence

! + - (unary operators)

first

* / %

second

+ - (binary operators)

third

< <= >= >

fourth

== !=

fifth

&&

sixth

||

seventh

last

Formatted Output with printf


#include <stdio.h>
void main (void)
Declaring variable (month) to be integer
{
int month;
Declaring variables (expense and
float expense, income; income) to be float (real number)
month = 12;
Assignment statements store numerical values
in the memory cells for the declared variables
expense = 111.1;
, separates string literal from variable names
income = 1000.0;

printf (Month=%2d, Expense=$%9.2f\n,month,expense);

27

Correspondence between variable names and


%(placeholder)...in string literal

Formatted Output with printf cont.

28

Formatted Input with scanf

29

Formatted Input with scanf cont.

30

Program Debugging
Syntax error
Mistakes caused by violating grammar of C
C compiler can easily diagnose during compilation
Run-time error
Called semantic error or smart error
Violation of rules during program execution
C compiler cannot recognize during compilation

Logic error
Most difficult error to recognize and correct
Program compiled and executed successfully but answer
wrong
31

Program Debugging Syntax Error


Snapshot
Failed to compile!

32

Program Debugging Run Time Error


Snapshot
Successfully compile but failed to execute !

33

Program Debugging Logic Error


Successfully compiled & executed with error!
Snapshot

PLT101 2013/2014
34

End Week 1 Session 2


Q & A!

3
5

Pop Quiz
Q1: Debug the following program:
#include <stdio.h>
int main()
{
int A, B, &Sum;
printf ("input first integer \n");
scanf ("%d", &A)
printf ("input second integer \n");
scanf ("%d", &B)
sum = A + B;
printf ("Sum is %s\t", A+B);
return 0;
}

36

Pop Quiz cont.


Q2: Write a pseudo code based on the following flow chart

37

Pop Quiz - Answer


Q1: Debug the following program:
#include <stdio.h>
int main()
{
int A, B, &Sum;
printf ("input first integer \n");
scanf ("%d", &A)
printf ("input second integer \n");
scanf ("%d", &B)
sum = A + B;
printf ("Sum is %s\t", A+B);
return 0;
}

38

//discard &
//missing semicolon
// missing semicolon
//capital S
//%d for decimal(int)

Pop Quiz Answer cont.


Q2: Write a pseudo code based on the following flow chart
Begin
Read user marks : x
if x is less than 40 points
print FAIL
else
print PASS
End

39

You might also like