+ All Categories
Home > Documents > CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Date post: 29-Dec-2015
Category:
Upload: everett-riley
View: 227 times
Download: 5 times
Share this document with a friend
66
CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1 BS (May 2013)
Transcript
Page 1: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

CHAPTER 4: The Basic of C

CSEB113 PRINCIPLES of PROGRAMMING

byBadariah Solemon

1BS (May 2013)

Page 2: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Topics1. C Tokens

– Reserved words, identifiers, string literals, operators, punctuators

2. Basic Data Types– int, float, double, char

3. Variables4. Constants5. Reading Data from the Keyboard

– Using scanf() function, placeholders, address operator &

6. Arithmetic Operators and Expressions– Types of operators, operator precedence, associativity rules

7. Single Character Data– getchar(), putchar(), fflush(stdin) functions

2BS (May 2013)

Page 3: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

C TOKENS

Topic 1

BS (May 2013) 3

Page 4: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Tokens & Types of Tokens• Token – the basic element on a C program recognized by the

compiler

BS (May 2013) 4

/* Example Case: ApplesAuthor: Mdm Badariah Solemon*/#include <stdio.h>int main(){

int Qty;double Cost=0.0, Total=0.0;

printf ("Enter quantity of apples purchased (in Kg):");scanf("%d", &Qty);

printf ("Enter the cost per Kg of apples (in RM per Kg):");scanf("%lf",&Cost);

Total = Cost * Qty;

printf("\nTotal cost of apples = %.2f\n",Total);

return 0;}

identifiersstring literals

reserved words

punctuation

operator

Page 5: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

1. Reserved Words• Keywords that identify language entities such

as statements, data types, language attributes, etc.

• Have special meaning to the compiler - MUST NOT be used as identifiers in our program.

• Must be typed in lowercase.• Ex: auto, double, else, void, int

BS (May 2013) 5

Page 6: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Task: Identify the KeywordsData Type-related Flow of Control-related Miscellaneous

intdoublefloat

ifelsewhile

enum

BS (May 2013) 6*Complete this table

Page 7: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

2. Identifiers• Words used to represent and reference

certain program entities (variables, constant, function names, etc).

• Also known as programmer-defined words.• Example:

BS (May 2013) 7

int myName; myName is program

variable.

void calculateTotal(int value); calculateTotal is a function

name.

#define TAXRATE 26 TAXRATE is a

constant.

Page 8: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Identifiers: Rules

BS (May 2013) 8

Rules Example

Can contain a mix of characters and numbers. However it cannot start with a number

H2o 2Ho

First character must be a letter or underscore Number1; _area

Can be of mixed cases including underscore character

XsquAre my_num

Cannot contain any arithmetic operators R*S+T

… or any other punctuation marks… #@%!!

Cannot be a C keyword/reserved word struct; printf;

Cannot contain a space My height

… identifiers are case sensitive Tax TaXTAX are different

Page 9: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Identifiers: Naming Styles• Avoid excessively short and cryptic names

such as x, or wt. • Use reasonably descriptive name such as student_name and StudentID.

• Use userscores or capital letters to separate words in identifiers that consist of two or more words.– Example: StudentName, student_name, or studentName

BS (May 2013) 9

Page 10: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

3. String Literal• A sequence of any number of characters surrounded

by double quotation marks “ ”. • Example:

• Example of usage in C program:

Produces output:

BS (May 2013) 10

“This is a string constant.”“Hello \”John”\.”

printf(“My name is David Beckham.\n”);

My name is David Beckham.

Page 11: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

4. Operators• Tokens that result in some kind of

computation or action when applied to variables or other elements in an expression.

• Example of operators:* + = - / < >

• Usage example:result = total1 + total2;

BS (May 2013) 11

Page 12: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

5. Punctuators• Symbols used to separate different parts of the C

program.• These punctuators include:

[ ] ( ) { } , ; “: * #

• Usage example:

– To be discussed when we come to the proper language feature in the coming chapters.

BS (May 2013) 12

main(){

printf(“Testing.”);}

Page 13: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Test Your Skill1. Valid/invalid – variables or constant

BS (May 2013) 13

Variables/ Constant

Valid/ Invalid?

Variable/ Constant

Valid/ Invalid?

CO2 const

_prs Formula #1

2ndDay Last.Name

First_name account#

NetPRIce engine 1

my name main

index Main

m*cee First+Last

mx_2ndcoverage typedef

Page 14: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

BASIC DATA TYPES

Topic 2

BS (May 2013) 14

Page 15: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Data Types• Are used to define a variable before its use.• The definition of a variable will assign storage

for the variable and define the type of data that will be held in memory location.

• Basic data types in C:1) int2) float 3) double4) char

BS (May 2013) 15

Page 16: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Basic Data Typesint

Whole numbers, positive and negativeEx:

BS (May 2013) 16

double

To declare floating point variable of higher precision or higher range of numbers - exponential numbers, positive and negativeEx:

float

Fractional parts, positive and negativeEx:

char*

Single character:1. Numeric digits: 0 - 92. Lowercase/uppercase letters: a - z and

A - Z3. White space4. Special characters: , . ; ? “ / ( ) [ ] { } *

& % ^ < > Ex:

double bigvalue = 12E-3;//equals to 12x10-3

char initial = ‘B’;

int number = 12;int sum = -3678;

float short = 0.000983;float income = 1234567890.12;

Page 17: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

VARIABLES

Topic 3

BS (May 2013) 17

Page 18: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

What are Variables?• Are memory locations within the computer which

allows pieces of data to be stored.• The word variable comes from the word vary, which

means that whatever you place within a variable can be changed.

• A variable can be viewed as a container used to store things (numbers, character, string etc )

• Types of operations:1. Declaring variables names2. Assigning variable values 3. Manipulating variable values

– ex: display on the screen

BS (May 2013) 18

Page 19: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Computer – Main Memory

BS (May 2013) 19

Hardware

• Is where anything that the computer is working with is kept.

• Memory may be conceptually viewed as an ordered sequence of storage location called memory cells.

• Information is stored in memory in bits• A memory cell is a group of bits called a byte• Each memory cell has a unique address

10001100 A910110010 A801110111 A711010000 A610010111 A500010110 A411010110 A310010101 A210010110 A1

01111110 B910110111 B811011100 B710010000 B600001010 B510010001 B410101110 B301110110 B210000110 B1

Ref: Tan and D’Orazio, C Programming for Engineering & Computer Science, New York: McGraw-Hill

Page 20: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Computer – CPU

BS (May 2013) 20

Hardware

• Does most of the work in executing a program

• The CPU inside a PC is usually the microprocessor

• Three main parts:1. Control Unit

Fetch instructions from main memory and put them in the instruction register

2. ALU (Arithmetic Logic Unit)Execute arithmetic operations

3. RegistersTemporarily store instructions or data fetched from memory

Page 21: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Declaring Variables• A variable is declared by specifying the DATA

TYPE of the variable name• Ex:

• Several variables of the same data type may be declared in the same statement.

• Ex:

BS (May 2013) 21

int Age;

Variable NameData Type

int Age, Weight;

Variable NamesData Type

Comma to separate variables

Page 22: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Assigning Values to Variable• A variable is assigned with a value using an

assignment operator =.• Ex:

• During program execution, may be conceptually viewed as:

BS (May 2013) 22

Variable Name Data Type Data Value Memory Cell Address*

Age int 17 ffff8

Weight int 60 ffff2

Age = 17;

17 is assigned to Age

Weight = 60;

60 is assigned to Weight

Page 23: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Assigning Values to Variables During Declaration

• Variables may be assigned with values even during the variables declaration.

• Ex:

BS (May 2013) 23

int Age = 17, Weight = 60;

Data Type

Comma to separate variables

int Age = 17;

Variable Name

Page 24: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Printing Variable Values• Use the printf() function to display the value of a variable

on the computer screen.• Syntax:

• FormatString is a combination of characters, placeholders and escape sequence.

• PrintList is any constants, variables, expressions, and functions calls separated by commas.

• Example:

BS (May 2013) 24

printf(FormatString, PrintList);

int age = 80;float cgpa = 4.00;printf(“Your age: %d\n”, age);printf(“CGPA: %f\n”, cgpa);printf(“My CGPA: %.2f\n”, cgpa);

placeholder

Your age: 80CGPA: 4.000000My CGPA: 4.00

Page 25: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Placeholders in printf() Function• Placeholders (or also known as format specifiers) always

begin with the symbol %• Are used to format and display the variable/constant

values on the screen• Common placeholders:

BS (May 2013) 25

Placeholder Data Type

%d int

%f double/float

%c char

%s String

Refer Table 12.2, pg 647 (Hanly & Koffman)

Page 26: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

More About Printing Variable Values

• Recall this syntax:

– FormatString can have multiple placeholders if the Printlist in printf() function has several variables.

• Example:

BS (May 2013) 26

#include <stdio.h>main(){

int age = 80;float cgpa = 3.512, weight = 60.4778;

printf(“Age: %d and CGPA: %.2f\n”, age, cgpa);printf(“CGPA: %.2f and Age: %d\n”, cgpa, age);printf(“CGPA: %.1f\tWeight2: %.2f\n”, cgpa, weight);printf(“Weight3: %.3f\t”, weight);printf(“Weight4: %.4f\n”, weight);}

printf(FormatString, PrintList);

Page 27: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Test Your Skill• Do hand-out exercise – declare & assign variables

• What happen if you try to print an int with %f or a float with %d?

• What is the output for the following program?

BS (May 2013) 27

#include <stdio.h>main(){

int yearS = 4;float cgpa = 3.88, gpa = 4.00;double

printf(“How long it takes to complete ur study?\n%d\n”,yearS);printf(“GPA\t\tCGPA\n”);printf(“%.2f\t\t%.2f”,gpa, cgpa);printf(“Excellent!\n”);printf(“Now, test your skill\n”);printf(“CGPA in 1 decimal point = %.1f\n”, cgpa);printf(“CGPA = %f\n”, cgpa)

}

Page 28: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

CONSTANTS

Topic 4

BS (May 2013) 28

Page 29: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Constants• Entities that appear in the program code as

fixed values.• Types of operations:

1. Declaring and assigning constant values2. Operating constant values

— Almost similar treatment like variables but CANNOT change the values after declaration!

BS (May 2013) 29

Page 30: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Declaring Constants1. As constant macro – created using a

preprocessor directives using define keyword – Ex:

2. Within a function using the const keyword.– Ex:

BS (May 2013) 30

#include <stdio.h>#define PI 3.14159#define DAYS_IN_YEARS 365 main(){ …

#include <stdio.h>main(){ const double KMS_PER_MILES = 1.609 …}

DATA TYPE?

Page 31: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Types of ConstantsInteger Constant

Positive or negative whole numbers Ex:

BS (May 2013) 31

Character Constant

A character enclosed in a single quotation markEx:

Floating-point Constant

Positive or negative decimal numbers Ex:

Enumeration

Values are given as a listEx:

#define LETTER ‘n’const char NUMBER = ‘1’;

enum Language { English Arabic Mandarin}

#define MAX 10const int MIN = -90;

#define PI 3.412const float PI = 3.412;#define VAL 0.5877e2const double VAL = 0.5877e2; //stands for 0.5877 x 102

Page 32: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Printing Constant Values• Similar to printing variable values

– What is the output of the program?

BS (May 2013) 32

#include <stdio.h>#define DAYS 365#define VAL 0.5877

void main(void){

const double PI = 3.412;

printf(“pi = %.3f\n”, PI);printf(“In a year, there are %d days\n”, DAYS);printf(“Value = %.4f\n”, VAL);

}

Page 33: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

READING DATA FROM THE KEYBOARD

Topic 6

BS (May 2013) 33

Page 34: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Using scanf() Function• To read data from the standard input device (usually

keyboard) and store it in a variable.• The general format is pretty much the same as printf() function.

• Syntax:

• InputList one or more variables addresses, each corresponding to a placeholder in the FormatString

• One placeholder for each variable in InputList.• The two or more variables in InputList must be separated by

commas.• Each element of InputList must be an address of a memory

cell(using prefix & address operator)

BS (May 2013) 34

scanf(FormatString, InputList);

Page 35: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Placeholders in scanf() Function• Are used to format and display the variable/constant

values keyed-in by the user• Common placeholders in scanf() function are very

similar to placeholders in printf() function:

BS (May 2013) 35

Placeholder Data Type

%d int

%f float

%lf double

%c char

%s String

Refer Table 12.2, pg 647 (Hanly & Koffman)

Page 36: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Example

BS (May 2013) 36

Address operator

int Age;double income;

printf(“Enter your age and income“);scanf(“%d %lf”, &Age, &income);

printf(“Your age: %d\n”, Age);printf(“Your income: %f\n”, income);

int Age; float income;

printf(“Enter your age: “);scanf(“%d”, &Age);

printf(“Enter income: “); scanf(“%f”, &income);

printf(“Your age is: %d\nIncome: %.2f”, Age, income);

If you want the user to enter more than one value, you serialise the inputs.

Page 37: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Test Your Skill

1) Write a simple C program that reads two integer values and print them on the screen in one line separated by one vertical tab. Follow this sample output:

2) Write a simple C program that reads 3 real numbers and print them on the screen in reverse order. Follow this sample output:

BS (May 2013) 37

Enter first integer: 80Enter second integer: 9980 99

Enter three real numbers: 5.6 7.8 9.3

In reverse order: 9.3 7.8 5.6

Page 38: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

ARITHMETIC OPERATORS AND EXPRESSIONS

Topic 5

BS (May 2013) 38

Page 39: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Arithmetic Expressions• A syntactically correct and meaningful combination

of operators and operands is known as an Expression.

• ‘=’ is the basic assignment operator• Syntax:

• Example:

BS (May 2013) 39

cityTax = CITYTAXRATE * grossIncome;

Variable = ArithmeticExpression;

assignment operator arithmetic operator

operands

Expression:

month = 12;

12 is assigned to variable month

Page 40: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Arithmetic Operators• There are 2 types of arithmetic operators in C:

1. Unary operators are operators that require only one operand.• Example:

2. Binary operators are operators that require two operands.• Example:

• Note that we CANNOT write arithmetic expressions like the following:

BS (May 2013) 40

operand

second = -first;prs = -34;

third = first / second;sum = 30 + 76;

operands

first / second = third;30 + 76 = sum;

XX

Page 41: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

1. Unary Operators

• Initial value of a is 10 and b is 5

BS (May 2013) 41

Operation/ Operators Expression End value of a

Positive + a = +b 5

Negative - a = -b -5

Increment ++a++ 10 ++a 11

Decrement --a-- 10 --a 9

prefix (before a variable)

postfix (after a variable)

Page 42: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Prefix/Postfix Increment• a++ or ++a is equals to a = a + 1 but they work

differently

BS (May 2013) 42

Prefix Increment (++a) Postfix Increment (a++)1. Add the value of a by 12. Return the value a

1. Return the value a2. Add the value of a by 1

Example:int a=9;printf(“%d\n”, a);printf(“%d\n”, ++a);printf(“%d”, a);

Output:91010

Example:int a=9;printf(“%d\n”, a);printf(“%d\n”, a++);printf(“%d”, a);

Output:9910

Page 43: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Prefix/Postfix Decrement• Similarly, --a or a-- is equals to a = a - 1 but they

work differently

BS (May 2013) 43

Prefix Decrement (--a) Postfix Decrement (a--)

1. Subtract the value of a by 12. Return the value a

1. Return the value a2. Subtract the value of a by 1

Example:int a=9printf(“%d\n”, a);printf(“%d\n”, --a);printf(“%d”, a);

Output:988

Example: int a=9; printf(“%d\n”, a); printf(“%d\n”, a--); printf(“%d”, a);Output:

998

Page 44: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

2. Binary Operators• If all operands in an arithmetic expression are of type double/float, the result is also of type double/float except for modulus operator.

• If all operands in an arithmetic expression are of type int, the result is also of type int.

• Value of a is 9BS (May 2013) 44

Operation/ Operators Expression End value of a

Addition + a + 2 11

Subtraction - a – 2 7

Multiplication * a * 2 18

Division / a / 2 4

Modulus % a % 2 1

Page 45: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Modulus Operator (%)• You could only use modulus (%) operation on

integer variables/integer division• Modulus will result in the remainder of an

operation• Example:

– 7 % 2 is 1

– But 2 % 7 is 2. Any idea why?

BS (May 2013) 45

72

3

6

1

-

7/2

7%2

integral

remainder

Page 46: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Example• A simple C program that find an average of

two real numbers.

BS (May 2013) 46

#include <stdio.h>void main(void){

float no1, no2, sum, avg;printf(“Enter three real numbers: “);scanf(“%f %f”, &no1, &no2);

sum = no1 + no2;avg = sum / 2;

printf(“Average: %.2f”, avg);}

Page 47: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Test Your Skill1) Write a program that sum up 4

integer numbers and display the computed sum.

2) Design pseudocode/flowcharts to solve the following problems and convert them into complete C programs:a) Compute and display the average of three

numbers.b) Read the value of the height, width and length of

a box from the user and print its volume.

BS (May 2013) 47

Page 48: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Compound Assignment Operator

• Are combinations of operators with the basic assignment operator =

• Initial value of a is 8:

BS (May 2013) 48

Operators Example Equivalent Expression Result+= a += 2 a = a + 2 10-= a -= 2 a = a - 2 6*- a *= 2 a = a * 2 16/= a /= 2 a = a / 2 4%= a %= 2 a = a % 2 0

Page 49: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Test Your Skill• What is the output of the following

program?

BS (May 2013) 49

#include <stdio.h>void main(void){

int first;printf("Enter a value: ");scanf("%d", &first);

printf("\nNew value is: %d\n\n", first+=4);printf("\nNew value is: %d\n\n", first*=4);printf("\nNew value is: %d\n\n", first-=4);printf("\nNew value is: %d\n\n", first%=4);

}

Page 50: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Operations of Mixed or Same Types1

BS (May 2013) 50

int

int

float

float

float

int

int

float

float

Examples:5 + 3 is 85/3 is 1 WHY?

5.2 + 3.1 is 8.35.0/3.0 is 1.6

5.2 + 3 is 8.25.0/3 is 1.65/3.0 is 1.6

Page 51: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Operations of Mixed or Same Types2

BS (May 2013) 51

Assigning real values to int or float variables:int m=0, n=0;float p=0.00, q=0.00;

m = 5/3;

p = 5/3;

n = 5/3.0;

q = 5/3.0;

int

float

int

float

int/int int5/3 is 1

int/float float 5/3 is 1.6

m is 1

p is 1.0

n is 1

q is 1.6

Page 52: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Type Casting• You can modify the way C uses types in arithmetic operations

by using cast operators. The syntax:

• Recall:

• So what can you do to ensure that the operation produces 1.6 instead of 1?

To ensure that you did not loose any data from the operation, you may apply type casting as follows:

BS (May 2013) 52

(type) expression

5/3 result in 1

•(float)5/3•5/(float)3•(float)5/(float)3•((float)5)/((float)3)

Page 53: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Guidelines in Writing Arithmetic Expressions

• If it is division operation, make sure it does not involve two integer variables or constants (unless you want the fractional part to be cut off)

• When writing your code, a float type variable is on the left side of an assignment statement. Example:

• When int type variable is on the left side of an assignment statement, make sure that the statement is meant to create an integer value.

BS (May 2013) 53

int sum = 87;float avg;

avg = sum / 4;

Page 54: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

C Rules for Evaluating Expressions

• We must know the C rules for evaluating expression when there is multiple mix of operators in the expression.

• In this example, which operator should be evaluated first?

• The rules for evaluating expressions are:1. Parentheses rule: all expressions in () must be evaluated

separately. Nested parentheses – innermost first . Parentheses can be used to control the order of operator evaluation

2. Precedence rule: specifies which of the operators will be evaluated first.

3. Associativity rule: specifies which of the multiple occurrences of the same operators will be evaluated first.

BS (May 2013) 54

s = x / y + z

Page 55: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Precedence and Associativity of Operations

• For details, refer to Appendix C (Hanly &Koffman)

• L – from left to right R – from right to left

BS (May 2013) 55

Precedence Operation Associativity

Highest (evaluated first)

Lowest (evaluated last)

[ ] ( )

postfix++ postfix--

prefix++ prefix-- unary+ unary- unary& unary*

* / %

binary+ binary-

= += -= *= /= %=

L

L

R

L

L

R

Page 56: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Example1

The order: Evaluation steps (assume initial value of s is 2, x is 9, y is 1, z = 2):

Step 1: s = 9 / 1 + zStep 2: s = 9 + 2Step 3: s = 11

BS (May 2013) 56

s = x / y + z

13 2

The order: Evaluation steps (assume initial value of i is 1, j is 7):

Step 1: i += 7 - 2Step 2: i = 6 (i += 5 i = 1 + 5)

i += j – 2

12 Other option?Use parentheses

Page 57: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Example2

Note:– The expression inside a parentheses will be evaluated first.– The associativity rule of parentheses is left to right

BS (May 2013) 57

The order: Evaluation steps (assume initial value of p1 is 4.5, p2 is 9.0, t1 is 0.0, t2

is 60.0):

Step 1: v = (9.0 – 4.5) / (t2 – t1)Step 2: v = 4.5 / (60.0 – 0.0)Step 3: v = 4.5 / 60.0Step 4: v = 0.075

v = (p2 – p1) / (t2 – t1)

1 3 24

Page 58: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Test Your Skill1 • Find output of the program segment

BS (May 2013) 58

...int i=5, c=10, x;

x = +i++;printf("a) x = %d, i = %d\n", x, i);

x = ++x;printf("b) x = %d, i = %d\n", x, i);

x = c++ + i;printf("c) x = %d, i = %d\n", x, i);

x = --c + --i;printf("d) x = %d, i = %d\n", x, i);

x = i + -x;printf("e) x = %d, i = %d\n", x, i);...

Page 59: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Test Your Skill2• Find output of the program segment

BS (May 2013) 59

...int x, y=5,z=10, s=3, p, q, r;

x = (x % 2) + (y – 3));printf("%d\n", x);

x = ++z + z * 2;printf("%d\n", x);

p = y * z – s + x / z;q = y * (z – s) + x / z;r = y * z – s + x / z;printf(“%d %d %d %d\n”, p, q, r, x);

...

Page 60: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

SINGLE CHARACTER DATA

Topic 7

BS (May 2013) 60

Page 61: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

The Set of C Characters• The characters that can be used to form words,

number and expressions (depend upon the computer on which

the program is run).• Are grouped into 4 categories:

BS (May 2013) 61

Letters

•Uppercase A to Z•Lowercase a to z

White Space

•Blank space•Horizontal tab (\t)•Carriage return (r)

•New line (\n)•Form feed (\)

Digits

•0 to 9

Special Characters

See next page

Page 62: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

C Special Characters

BS (May 2013) 62

Page 63: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Working with char Data Type

• Declaring character variables. Example:

• Assigning a character constant to character variables. Example:

• Using printf() function to print characters. Example:

• Using scanf() function to input characters. Example:

BS (May 2013) 63

char c1;char c2, c3, c4;

c1 = ‘p’;c2 = ‘\n’;c3 = ‘#’;

printf(“%c\n”, c1);printf(“%c %c”, c1, c2);

scanf(“%c %c ”, &c1, c2);scanf(“%c%c”, &c3, &c4);

Each character is enclosed in single quotes ‘ ’

No spaces in the string literal

Page 64: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Character Input Output Functions

• getchar() – to read a character from standard input• putchar() – to write a character to standard output• Example:

• To be discussed further in Chapter 8: Characters Array (String)

BS (May 2013) 64

#include <stdio.h>main(){

char myC;printf(“Please type a character: “);myC = getchar();printf(“\nYou have typed this character:

“);putchar(myC);printf(“\n”);

}

Page 65: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Input Buffer & Flushing the Buffer

• The getchar() function works with the input buffer to get the information typed at the keyboard. – Buffer – a portion of memory reserved for temporarily holding

information that is being transferred.

• When getchar()function is used, it is easy to see an execution that is different than it should be.

• So, what you can do is to flush or empty the input buffer by using fflush (stdin); statement.

• Example:

BS (May 2013) 65

char c1, c2;printf(“Enter 2 characters:”);fflush(stdin);c1 = getchar();c2 = getchar();fflush(stdin);

* This may not work for certain OS (e.g., LINUX)

Page 66: CHAPTER 4: The Basic of C CSEB113 PRINCIPLES of PROGRAMMING by Badariah Solemon 1BS (May 2013)

Summary• Basic elements (tokens) in C: reserved words, identifiers, string literals,

operators, punctuators• Working with variables and constants of types int, float, double,

char• Pre/post fix (increment and decrement)- effect the result of arithmetic

expressions• Reading data using scanf() function

– Placeholders and address operator &• The C rules when evaluating expression with multiple mix of operators in

arithmetic expression:– Parentheses rule, precedence rule & associativity rule

• Working with single character data including getchar() and putchar() functions– empty the input buffer by using fflush (stdin); statement

BS (May 2013) 66


Recommended