You are on page 1of 46

CHAPTER 2

STRUCTURE OF C
Structure of C 1
OBJECTIVES
In this chapter you will learn:

The basic elements of C


To create C statements or expression by using the
representation of identifier, variable, constant, data types and
pre-processor directives
To form arithmetic expression using numeric values and
operator
To perform computations, entering data and displaying results
To construct a simple C Program

Structure of C 2
Subtopics
Introduction to C
o Why you learn C
o Steps in developing a C program
o Beginning Concept
o Write My First C Program

C Fundamentals
o Keyword o Data types
o Identifier o Preprocessor Directives
o Variable & Constant o Formatting Input

Structure of C 3
Subtopics

Operator in C
Assignment
Arithmetic
Equality, Relational & Logical
Increment &Decrement
Cast

Structure of C 4
2.1 Introduction

Introduced at Bell Labs in 1972 by Dennis Ritchie


as a successor of the language called B (Basic Combined
Programming Language BCPL).

2.1.1 Why C ?

Structured programming and proper programming techniques


Syntax & Coding style is simple
Suitable for complex engineering applications
Portable : can be executed on different OS

Structure of C 5
Steps in Developing C Program

A typical High-Level Language Dev.

Editor

Source File program.c


You have to create your program and
compile it before it can be executed.
Preprocessor
Create/write & modify your program

Modified Source Code in Memory (C Source code)


Compiler Visual C++ editor or etc.

Program Object Code File program.o


Other Object Code Files (if any)

Linker

Executable File

Structure of C 6
Steps in Developing C Program

Preprocessor
o A program that is used to modify the source code in memory
according to preprocessor directive (example : #include)
embedded in the source code.
o Strip comments & unnecessary white spaces in the source code.

Compiler
o Converts source ( human-readable) program to
object (machine-readable) program
Linker
o Converts object program to
o executable program

Structure of C 7
Basic in C Language

In general, a C program consist of


o program comments
o preprocessor directives
o data types
o type declarations
o named constants
o statements
o function(procedure)

Structure of C 8
Basic in C Language
preprocessor directives
int main(void)
{
declarations;
statements;
}

Every C language must have at least one function


namely main().
Structure of C 9
Concept in C Language
ITEMS PURPOSES
main Begin the C Program

() Must be used after main or function name.


/* */ Comment -Text surrounded by /* and */ is ignored
by computer. Used to document programs and
improve program readability.

; Every C statements must end with semicolon, known


as statement terminator
{ } Braces { and } indicate a block
-The bodies of all function must be contain in braces

- Shows begin/end the body of every function.

Structure of C 10
My First C Program
Preprocessor Program comment
directive /* My first programming in C */
/* main function*/
#include <stdio.h>
int main ( ) {
printf (Welcome to C !\n); Function Body
printf (Have Fun);
Output return 0;
statement } /*end main function */

So, what is the output displayed on the


screen ??
Structure of C 11
The very basic of C
Programming
/* Aturcara ini mencetak ucapan A
Selamat Datang ke UTHM */

#include <stdio.h> B

void main ()
{
printf ( Selamat Datang ke UTHM!\n ); C
}

Part A Part B Part C


Called as comment. Preprocessor directive. Main function
Can used the /* */
Start with # symbol
#include <stdio.h>
or //

Structure of C 12
2.2 C Fundamentals
Keyword / reserved word
o identify language entities, such as statements,
data types, and language element attributes.
o have special meanings to the compiler.
(have predefined uses)
o must be typed fully in lowercase.
o 32 words defined as keywords in C
o Example : const, double, int, return

Structure of C 13
C Fundamentals
Identifiers
o Standard identifiers
special meaning in C
defined in stdio library
can be redefined
User defined Identifiers
defined by users

Structure of C 14
Rules : User Defined Identifiers

Can consists of letters( A to Z/ a to z), digits and


underscore character
The first character must be a letter or an
underscore
No length limitation. C compiler can recognize
only the first 32 characters
There can be no blank space
Reserved/keywords cannot be use ad identifiers.
Identifiers are case-sensitive.
Identifiers are distinct.

Structure of C 15
C Fundamentals
Variable
o Represent certain value of a certain data type and store
data such as numbers and letters.
o The number or letter or other data item in a variables is
called its value.
o The general syntax for declaring variables is :

datatype variableName;

e.g :
char category;
int num;
double weight;
float price;

Structure of C 16
Variable
o If variables are of the same type, they can be declared together, as follows :

datatype var1, var2, var3,.varn;


e.g :
double x, y, z;

o You cannot declare the same variable more than once; therefore, the second
declaration below is invalid because y is declared twice :

e.g : int a, b, c;
int b;

o Initializing variable
After declaring a variable it should be initialized with a suitable value

eg : float price; /*declaring variable*/


price = 4.50; /*initializing variable*/

Structure of C 17
C Fundamentals
Constant
Constants are entities that appear in the program code as fixed values.
o Types of constants:
o Integer (-15, 0, +250, 7550)
o Floating point
(20.35 = 0.2035 x 102 = 0.2035E+2 = 0.2035e+2)
o Character (1, n, A)
o String Constant C Programming is easy

o Named Constant
o Declared constant (in a function body)
Example : const float PI = 3.141;

o Define constant (#define pre-processor directive )


Example : #define PI 3.141

Structure of C 18
C Fundamentals
Data types
o A set of data with values having predefined characteristics

Primitive (basic data type)


int, double, float, char

User defined (define based on the fundamental data type)


Derive (combination data types)

o Examples of primitive data types


long int number_of_student;
long total_book;
float monthly_payment;
double field_area;

Structure of C 19
C Fundamentals
Preprocessor Directives
o commands that give instructions to the C preprocessor,

whose job is to modify the text of a C program before it is


compiled
o begins with a symbol (#)

o #include directive

gives a program access to a library


example : #include<stdio.h>
o #define directive

associate the constant macro


example : #define FULL_MARK 100

Structure of C 20
C Fundamentals
Formatted Output & Input

o Formatted Output
use printf Function
prints information to the screen
Required argument
control string
specific conversion specifier
Example :

double angle = 45.5;


printf(Angle = %.2f degrees \n, angle);
Output???

Structure of C 21
C Fundamentals
o Formatted Input
Use scanf Function

inputs values from the keyboard

required arguments

control string
memory locations that correspond to the specifiers in the
control string
Example:
double distance;
char unit_length;
scanf("%1f %c", &distance, &unit_length);

It is very important to use a specifier that is appropriate for the


data type of the variable

Structure of C 22
2.3 Operator in C
Assignment Operator
o Use simple equal (=) sign
o Format
variable_name = expression;
o The expression can be a single variable or a literal, or it may
contain variables, literals and operators

Example :
num1 = 5;
num2 = 6;
num2 = num2 + 12;
num4 = (num1 + 2) / 2;
* Use C shortcut to simplify your assignment statement

Structure of C 23
Assignment Operator

int m = 3, n = 2;
double x, y, p = 2.0;
x = m / p;
y = m / n;

What happened to the above coding / program ?


How to allocate the memory to each variable ?

Structure of C 24
Assignment Operator

m n

x y

Then, whats next ?


Structure of C 25
Assignment Operator : Memory
allocation
m 3 n 2

p 2.0

x 1.5 y 1.0

First, value of m and n will be declared as integer ( data type ).


However, the integer value of m and n cannot be used because
the output for m / p ( which is x ) and m / n ( which is y ) are
already declared as double.
Try this :
x = 9 * 0.5;
n = 9 * 0.5;

Structure of C 26
Operator in C
Arithmetic
o Arithmetic Operator
1. Unary
o Unary plus (+) & unary minus (-)
Eg : first = +x;
second = -x;
o Increment & Decrement (discuss later in slide 28)

2. Binary
o manipulate two operand (constants, variables or other arithmetic
expression )
o Use operator +, -, *, / and %
Arithmetic expression
Eg :
circe_area = PI *radius *radius;

constant variable

operand

Structure of C 27
Binary Arithmetic Operator

Example 1 : Assume x = 6 , y =2

Operator Meaning Arithmetic Value of z After


Expression Execution
+ Addition z=x+y 8
- Subtraction z=x-y 4
* Multiplication z=x*y 12
/ Division z = x/ y 3
% Remainder z=x%y 0

Structure of C 28
Division and remainder for integer
number
3 / 15 = 0 3%5=3
15 / 3 = 5 4%5=4
16 / 3 = 5 5%5=0
17 / 3 = 5 6%5=1
18 / 3 = 6 7%5=2
0/4=0 8%5=3
4 / 0 ( undefined) 15 % 0 ( undefined)

Structure of C 29
Arithmetic

o Precedence & Associatively


If there are a few operators (multiple operators) in an
expression, C will use Rules of operator precedence

Example :
int a, b, c, d, e;
a = 20, b = 15, c = 10, d = 6;

e = a * (b c) % 30 + (c + d) ;
3 1 4 5 2
steps

Structure of C 30
Precedence &
Associatively
a. Parentheses rule: ( )
b. Operator precedence rule :
Rules
! ++ --
* / %
+ -
< <= > >=
== !=
&& || =

c. Associativity rule
right associativity unary operator usage will be evaluated
from right to left if located at the same level.
left associativity binary operator usage will be evaluated
from left to right if located at the same level.
Structure of C 31
Precedence &
Associatively
Eg : x * y * z + a / Rules
bc*d
What can we do to modify the above
expression ?

Structure of C 32
Precedence & Associatively
Rules
It would be better if the expression is added
with parentheses as below :
(x * y * z) + (a / b) (c * d)
Try this :
z (a + b / 2) + w * y

Structure of C 33
Operator in C
Equality, Relational & Logical
Standard Algebraic C Operator
Operator

Equality
= == Use to compare
not = != values forming
Relational relational expressions
> >
>= Example :
< <
a>b
c != 0
<=
Logical
AND &&
OR ||
NOT !

Structure of C 34
Operator in C

Increment & Decrement


o C has special shortcut in incrementing/decrementing
a variable by one (1) . Consider this following statement :

num = num + 1 ,
can be shorten to num++;

Structure of C 35
Operator in C

Cast
o Casting is an operation that converts value of one data type into
a value of another data type.
o
Syntax of cast operation : (type) variable/Expression
Example :

double a = 3.0; b = 2.0;


int c;
/* syntax error occur */
c = a % b;
Solution :
c = (int)a % (int)b;

Structure of C 36
Casting operation

int total_score, num_students;


double average;

average = total_score / num_students;

average = (double)total_score / (double)


num_students;

average = (double) (total_score / num_students);

Structure of C 37
Wrting mathematic formula in
C Eg :
a = bc a = b * c;
m = y-b m = (y-b)/(x-a);
x-a
Try this : b-4ac
a+b-c
a+b
c+d
1
1+x

Structure of C 38
Example 1 :

#include <stdio.h>
#define STUDENT 5

void main( ) {
int total = 456;
double avg1, avg2;

avg1 = total/ STUDENT;

avg2 = (double)total/ STUDENT;

printf(" Average 1 : %.2f",avg1);


printf("\n Average 2 : %.2f\n",avg2);
}

Structure of C 39
Example 2:
#include <stdio.h>
void main( )
{ int a;
int b;
int c;
int jum;

printf(Selamat Datang. \nAturcara ini menjumlahkan 3


nombor.\n);
printf(Masukkan 3 nombor dalam bentuk: nnn nnn nnn
<enter>\n);
scanf(%d %d %d, &a, &b, &c);

jum = a + b + c;
printf(Jumlah adalah: %d\n\n, jum);
prinf(Terima kasih.\n);
}

Structure of C 40
Output for example 2 :
Selamat
Selamat Datang.
Datang.
Aturcara
Aturcara ini
ini menjumlahkan
menjumlahkan 33 nombor.
nombor.
Masukkan
Masukkan 33 nombor
nombor dalam
dalam bentuk:
bentuk: nnn
nnn nnn
nnn nnn
nnn
<enter>
<enter>
11
11 2222 33
33

Jumlah
Jumlah adalah:
adalah: 66
66

Terima
Terima kasih.
kasih.

Structure of C 41
Example 3 :
#include <stdio.h>

void main () the arithmetic expression will


{ be calculated and the output
int nilai1; will be printed on the monitor
float nilai2; screen.
nilai1 = 10;
nilai2 = 5.5;

printf ( Nilai pertama = %d\n, nilai1 );


printf ( Nilai kedua = %f\n, nilai1 nilai2 );
}

Nilai
Nilai pertama
pertama == 10
10
Nilai
Nilai kedua
kedua == 4.500000
4.500000

Structure of C 42
End of Chapter 2

Yes !! Thats all?


Whats next???

Question?
Question?
Question?

Structure of C 43
Exercise :

Which one is correct ?

Jumlah Besar ( )
jumlahBesar ( )
jumlah_besar ( )
8JumlahBesar ( )

Structure of C 44
Exercise :

What is the value for n and z ?

int k = 5, m = 4, n;
double x =1.5, y = 2.1, z;

n = k + x;
z = k / m;
n = x * y;
Structure of C 45
Answer :

n = k + x; 5 + 1.5 = 6.5
z = k / m; 5 / 4 =1
n = x * y; 1.5 * 2.1 = 3.15

Structure of C 46