Ch2 introduction to c

34
DEE 2112 Sem 1 0910 1 CHAPTER 2 INTRODUCTION TO C

description

 

Transcript of Ch2 introduction to c

Page 1: Ch2 introduction to c

DEE 2112 Sem 1 0910 1

CHAPTER 2INTRODUCTION TO

C

Page 2: Ch2 introduction to c

DEE 2112 Sem 1 0910 2

OBJECTIVES

In this chapter you will learn:

• The C Fundamental Elements• 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

Page 3: Ch2 introduction to c

DEE 2112 Sem 1 0910 3

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

Page 4: Ch2 introduction to c

DEE 2112 Sem 1 0910 4

Steps in Developing C Program

A typical High-Level Language Dev.

Editor

Preprocessor

Compiler

Linker

Source File program.c

Modified Source Code in Memory

Program Object Code File program.o Other Object Code Files (if any)

Executable File

You have to create your program and compile it before it can be executed.

•Create/write & modify your program

(C Source code)

Visual C++ editor or etc.

Page 5: Ch2 introduction to c

DEE 2112 Sem 1 0910 5

Steps in Developing C Program

Preprocessoro 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.

Compilero Converts source ( human-readable) program to object (machine-readable) program

Linkero Converts object program to executable program

Page 6: Ch2 introduction to c

DEE 2112 Sem 1 0910 6

Beginning Concept

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)

Page 7: Ch2 introduction to c

DEE 2112 Sem 1 0910 7

Beginning Concept :Program Structure

preprocessor directivesint main(void){

declarationsstatements

return 0;}

Every C language must have at least one function namely main().

refer table 2.1 :Defining a main() function

Page 8: Ch2 introduction to c

DEE 2112 Sem 1 0910 8

Beginning Concept

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.

Page 9: Ch2 introduction to c

DEE 2112 Sem 1 0910 9

My First C Program

/* My first programming in C */

/* main function*/

#include <stdio.h>

int main ( ) {

printf (“Welcome to C !\n”);

printf (“Have Fun”);

return 0;

} /*end main function */

Output display on the screen ? ? Refer Example 2.1 for more examples

Program commentPreprocessor directive

Output statement

Function Body

Page 10: Ch2 introduction to c

DEE 2112 Sem 1 0910 10

2.2 C Fundamentals

Keywordo 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 (see Table 2.2)

Example : const, double, int, return

Page 11: Ch2 introduction to c

DEE 2112 Sem 1 0910 11

C Fundamentals

Identifierso Standard identifiers

• special meaning in C • defined in stdio library• can be redefined (disable C to use it for original

purpose)

o User defined Identifiers• defined by users

Page 12: Ch2 introduction to c

DEE 2112 Sem 1 0910 12

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. • Identifies, are distinct.

See Table 2.3 ( Module C)

Page 13: Ch2 introduction to c

DEE 2112 Sem 1 0910 13

C Fundamentals : Variable & Constant

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;

Page 14: Ch2 introduction to c

DEE 2112 Sem 1 0910 14

Variableo 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*/

Page 15: Ch2 introduction to c

DEE 2112 Sem 1 0910 15

C Fundamentals : Variable & Constant

ConstantConstants 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

Page 16: Ch2 introduction to c

DEE 2112 Sem 1 0910 16

C Fundamentals

Data typeso A set of data with values having predefined characteristics

• Primitive (basic data type)• int, double, float, char ( see table 2.5 for more detail)

• User defined (define based on the fundamental data type)• Derive (combination data types)

o Examples of primitive data types

int number_of_student;

int total_book;

float monthly_payment;

double field_area;

Page 17: Ch2 introduction to c

DEE 2112 Sem 1 0910 17

Primitiva Data Types

Data Types Type Specifier Size in bits

int Integers 16

float Floating point numbers 32

double Precision floating point numbers

64

char Characters 8

void Null (without no values) 0

Page 18: Ch2 introduction to c

DEE 2112 Sem 1 0910 18

Integer

Integer Type Bait Range

short int 2 -32,767 . . 32,767

unsigned short int 2 0 . . 65,535

int 2 -32,767 . . 32,767

unsigned int 2 0 . . 65,535

long int 4 -2,147,483,647 . . 2,147,483,647

unsigned long int 4 0 . . 4,294,967,295

 

Page 19: Ch2 introduction to c

DEE 2112 Sem 1 0910 19

C Fundamentals

Preprocessor Directiveso 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

Page 20: Ch2 introduction to c

DEE 2112 Sem 1 0910 20

C Fundamentals

Formatted Output & Inputo 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???

* See example 2.5 for more details

Page 21: Ch2 introduction to c

DEE 2112 Sem 1 0910 21

/*variable declaration & initialization */int mark = 95;char grade = ‘A’;

/* Displaying text*/printf (“C is interesting ”);

/*Displaying a number in text */printf (“I got %d marks for C subject”, mark);

/*Displaying a character in text */printf (“Therefore %c is my grade”, grade);

/*Displaying multiple numbers in text*/printf (“My cpa is %f and my gpa is %f”, 3.90, 3.85);

Page 22: Ch2 introduction to c

DEE 2112 Sem 1 0910 22

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("%lf %c", &distance, &unit_length);

It is very important to use a specifier that is appropriate for the data type of the variable

See Table 2.6 :The printf and scanf conversion specifiers

Page 23: Ch2 introduction to c

DEE 2112 Sem 1 0910 23

/* calculate sum of two numbers */#include <stdio.h>int main(){

float x,y,sum;printf (“Please enter two floating numbers:”);scanf("%f", &x); // read 1st numberscanf("%f", &y); // read 2nd numbersum = x + y; // totalprintf("x+y = %f\n", sum); //display answer as floatreturn 0;

}

Page 24: Ch2 introduction to c

DEE 2112 Sem 1 0910 24

Conversion Specifiers

Variable Type Type Specifier

Decimal Integer %d or %i

Floating point numbers %f

Precision floating point numbers (DOUBLE)

%lf

Characters %c

String of characters %s

Page 25: Ch2 introduction to c

DEE 2112 Sem 1 0910 25

2.3 Operator in C

Assignment Operatoro Use simple equal (=) signo 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

Page 26: Ch2 introduction to c

DEE 2112 Sem 1 0910 26

Operator in C Arithmetic

o Arithmetic Operatoro Unary

o Unary plus (+) & unary minus(-) first = +x; second = -x; o Increment & Decrement

o Binaryo manipulate two operand (constants, variables or other arithmetic

expression )o Use operator +, -, *, / and %

circe_area = PI *radius *radius;

Arithmetic expression

constant variable

operand

Page 27: Ch2 introduction to c

DEE 2112 Sem 1 0910 27

Binary Arithmetic Operator

Example 1 : Assume x = 6 , y =2

Operator Meaning Arithmetic Expression

Value of z After 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

Page 28: Ch2 introduction to c

DEE 2112 Sem 1 0910 28

Arithmetic

o Precedence & Associatively

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

( refer table 2.8)

Example : Let us do it together 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 2steps

Page 29: Ch2 introduction to c

DEE 2112 Sem 1 0910 29

Operator in C Equality, Relational & Logical

Standard Algebraic Operator

C Operator

Equality

= ==

not = !=

Relational

> >

≥ >=

< <

≤ <=

Logical

AND &&

OR ||

NOT !

Use to compare values forming

relational expressions

Example : a > bc != 0

Page 30: Ch2 introduction to c

DEE 2112 Sem 1 0910 30

Operator in C

Increment & Decremento C have special shortcut in incrementing/decrementing

a variable by one (1) . Consider this following statement :

num = num + 1 ,

can be shorten to num++;o Try to evaluate the prefix and postfix examples in

Table 2.11

Page 31: Ch2 introduction to c

DEE 2112 Sem 1 0910 31

Prefix dan Postfix

• Contoh:1. i = 5;

j = i++ - 2;

2. i = 5;

j = ++i – 2;

5i j

5 3i j

6 3i j

5i j

6i j

6 4i j

Page 32: Ch2 introduction to c

DEE 2112 Sem 1 0910 32

Operator Precedence and Associativity

Operators Associativity

() L – R

++ -- + - ! R – L

* / % L – R

+ - L – R

< <= >= > L – R

== != L – R

&& L – R

|| L – R

?= R – L

= += -= *= /= %= L – R

Highest

Lowest

Page 33: Ch2 introduction to c

DEE 2112 Sem 1 0910 33

Operator in C

Casto 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, c;/* syntax error occur */c = a % b; Solution :c = (int)a % (int)b;

Page 34: Ch2 introduction to c

DEE 2112 Sem 1 0910 34

Example C Program

#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); }