Sei sulla pagina 1di 63

ENG 054: COMPUTING ENGINEERING II

Chapter 3 : Introduction to C Programming

Objectives :
1. To understand the basic components of C program 2. To introduce the concepts of - Data types - Identifiers : variables & constants - Arithmetic operators 3. To introduce standard input & output function
Juliana Jaafar CSC 099 Semester 2 2011/2012

Components of C Program
C program have parts and components that serve specific purposes BUT, the parts of C programs are not always in the same place

Juliana Jaafar CSC 099 Semester 2 2011/2012

Example of C Program

Juliana Jaafar CSC 099 Semester 2 2011/2012

Output of C program

output

Juliana Jaafar CSC 099 Semester 2 2011/2012

Example :
Write a program to calculate and display an area of a cylinder side. Area of cylinder side is calculated using the following formula :Area of cylinder = 2rh ; where r is the radius and h is the height. Your program will calculate the area of cylinder side based on the given input (i.e radius and height) from the user.

Structure of a C Program
Juliana Jaafar 2011/2012

//Written by: Rosmiza Wahida /*This program is to calculate the area of a cylinder*/ #include <stdio.h> #define pi 3.142 float A_cyl; int main() { float radius, height; printf(Please enter radius: ); scanf(%f,&radius); printf(Please enter height: ); scanf(%f,&height); A_cyl = 2*pi*radius*height; printf(Area for the cylinder is %f , A_cyl); return 0; }

Comments

Preprocessor directive

Global declaration

main() function

Local declaration

Statements

Function body

Return Statement

Juliana Jaafar CSC 099 Semester 2 2011/2012

Preprocessor Directive
Will be read first before the program is compiled
Indicated by pound sign (#) together with keyword
#include to include the contents of another file

#define to define global variable/constant


** No space between # and include

Juliana Jaafar CSC 099 Semester 2 2011/2012

Preprocessor Directive
#include <stdio.h>
stdio.h
Is the name of the file that is to be included. Dot h indicates the type of the file header file Allow C program to display output on the screen printf() and read input from the keyboard scanf()

#define pi 3.142
pi - Name of constant 3.142 value of the constant
Juliana Jaafar CSC 099 Semester 2 2011/2012

10

main() function
C Program can have one or more functions, exactly one MUST be main() function int main()
int stands for Integer. It indicates that the function sends an integer back to operating system when it is finished executing main() the name of the function

MUST be followed by set of braces ({ }) indicates a block, the beginning and ending of a function
All statements (function body) that make up a function are enclosed in a set of braces
Juliana Jaafar CSC 099 Semester 2 2011/2012

11

Comments
Use : to document programs and improve program readability
Help other people read and understand others program

IGNORED by C compiler and DO NOT cause any machine-language object code to be generated. DO NOT cause the computer to perform any action when the program is run. CAN be put ANYWHERE in the program
Juliana Jaafar CSC 099 Semester 2 2011/2012

12

Comments
Two format
Line comment
Marked by two slashes (//) at the beginning of comment For short comment in a single line Example:
//Written by : Rosmiza Wahida

Block comment
Marked by opening token(/*) and closing token (*/) For long comment Example :
/*This program is to calculate the area of a cylinder*/

Comments CANNOT be nested (comments inside comments)


Juliana Jaafar CSC 099 Semester 2 2011/2012

13

Function Body
Enclosed by a set of braces ({ }) Function contains
Local declaration
Declaration of data that will be used for the function/program Example :
float radius, height;

Statements @ Program body


Set of instructions of what the function/program should do

Return Statement
Return value that sends back to operating system Example :
return 0; ** 0 usually indicates that a program executes successfully
Juliana Jaafar CSC 099 Semester 2 2011/2012

14

Common Programming Language Elements


Syntax
Rules that must be followed when constructing a program

Lines
A line is a single line appear in the body of program

Statement
A complete instruction that causes the computer to perform some action

Juliana Jaafar CSC 099 Semester 2 Juliana 2011/2012 Jaafa CSC 099 Semester 2 2011/2012

15

Common Programming Language Elements


Keywords (Reserve Words)
Words that have special meaning and used for intended purpose

Programmer-Defined Identifier (Identifier)


Words/names defined by programmer. Symbolic names refer to variables or functions

Operators
Operator perform operations on one or more operands

Punctuations
Punctuation characters mark the beginning or ending of a statement, or separate item in a list
Juliana Jaafar CSC 099 Semester 2 2011/2012

16

Punctuations
Comma (,) use to separate item in a list
Use to separate item in a list Example :
float radius, height;

Semicolon (;)
Use at the end of a complete instruction Example :
float radius, height; printf(Please enter radius: ); A_cyl = 2*pi*radius*height; return 0;
Juliana Jaafar CSC 099 Semester 2 2011/2012

17

Reserve Word/Keyword
Special words reserve for C Program which have specific meaning and purpose CANNOT be used as identifiers or variable name Appear in lower case
C and C++ Reserved Words auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

Juliana Jaafar CSC 099 Semester 2 2011/2012

18

Identifiers
Allows programmers to NAME data and other objects in the program
variable, constant, function etc. Rules in naming identifiers MUST consist ONLY of alphabetic characters (uppercase or lower case), digits and underscores (_) First character MUST be alphabetic character or underscore CANNOT contain spaces CANNOT duplicate with any reserved word

** C is CASE-SENSETIVE
this means that NUM1, Num1, num1, and NuM1 are Juliana Jaafar four completely different name. CSC 099 Semester 2 2011/2012

19

Example of Valid & Invalid Identifiers


Valid Identifiers
A student_name _aSystemName Pi Al stdntNm anthrSysNm PI

Invalid Identifiers
$sum // $ is illegal 2names // cant start with 2 stdnt Nmbr // cant have space int // reserved word

Juliana Jaafar CSC 099 Semester 2 2011/2012

20

Variables
Variable names correspond to locations in the computer's memory Every variable has a NAME, a DATA TYPE, a SIZE and a VALUE A variable is created via a declaration where its name and type are specified. Example :
int integer1, integer2, sum;

Whenever a new value is placed into a variable (through scanf(), for example), it replaces (and destroys) the previous value
Juliana Jaafar CSC 099 Semester 2 2011/2012

21

Variable Declaration
Specifies in the memory to reserve a specific space for the variable that have the specific location and can store specific data type. MUST be declared before the executable of the statement Variable need to FIRST declare before it being used Syntax : data type variable name; Example int maxItems = 0; float payRate; double tax; char code; int a, b; // equivalent to int a; int b; Juliana Jaafar CSC 099 Semester 2 2011/2012

22

Example of Variable in Memory

long int

Juliana Jaafar CSC 099 Semester 2 2011/2012

23

Data Types
Variables are classified according to their data type
Determine the kind of information stored in variables Address, phone numbers, price, distance, and etc.

Functions also have types which determine by the data it returns C Program have 5 standard data types: void int Integer e.g. 1244,-87 char Character e.g a, A double Floating-point e.g 0.5678, -3.25 float : Floating-point (less precision)

Juliana Jaafar CSC 099 Semester 2 2011/2012

24

Data Type - void


Has no values and operations
Usually use for function Example : void printMessage()

Both set of values are empty

Juliana Jaafar CSC 099 Semester 2 2011/2012

25

Data Type - char


Use for storing character
Stored in memory as 1-byte integer data type WHY? Each printable and non-printable character is represented by a unique number in computer memory.

Observe the output!!

Juliana Jaafar CSC 099 Semester 2 2011/2012

26

Numeric Data Type


In C Program, numeric data types are broken into 2 categories: Integer
Whole numbers Example : 12, 157, -34 and 2

Floating point
Numbers that have decimal point Example : 23.7, 189.0231 and 0.987

Juliana Jaafar CSC 099 Semester 2 2011/2012

27

Numeric Data Type


Both Integer and Floating-point data type can be broken into more classifications Primary consideration for selecting data type: The largest and smallest number that maybe stored in the variable How much memory does the variable use Whether the variable stores signed or unsigned numbers The number of decimal places of precision the variable has

The size of variable is the number of bytes of memory it uses. (> varible > range can hold)

28

Integer Data Type


To store WHOLE NUMBER without fraction C program supports 3 different sizes of integer short int int long int
Type Byte Size

short int unsigned short int int unsigned int long int
unsigned long int

2 2 2 2 4
4

Minimum Value -32,768 0

Maximum Value

32,767 65,535 32,767 65,535 2,147,483,647


4,294,967,295

-32,768 0 -2,147,483,648
0

29

Floating Point Data Type


To store FLOATING-POINT number C program supports 3 different sizes of integer float double long double
Type
float double long double

Byte Size
4 8 16

Precision
6 15 19

Range
10-37 ..1038 10-307 ..10308 10-4931 ..104932
Juliana Jaafar CSC 099 Semester 2 2011/2012

30

Variable Initialization
To establish the first value that the variable will contain Syntax :
data_type variable_name = value;

Example :
int count = 5; int sum = 0; int count=0 , sum = 0; char letter = B;
Juliana Jaafar CSC 099 Semester 2 2011/2012

31

Constants
To define values that CANNOT be changed during the execution of a program Types of constant
Integer constant Float constant Character constant String constant Symbolic constant
Juliana Jaafar CSC 099 Semester 2 2011/2012

32

Constants
3 ways of defining a constant
Literal Constant Defined Constant using preprocessor Defined Constant using const

Juliana Jaafar CSC 099 Semester 2 2011/2012

33

Literal Constants
An unnamed constant used to specify data If the data cannot be changed, it can simply code the value itself in a statement Example :
A 5 a+5 3.1435 Hello // a char literal // a numeric literal 5 // numeric literal // a float literal // a string literal

34

Defined Constants
2 ways : Using preprocessor : #define
Example : #define pi 3.142

Using keyword : const


Example const int a = 1;

35

Assignment Operator (=)


To assign the value of variable or expression into to a variable. Example:
a = b; result = n1*n1; areaOfCircle = 3.142 * r * r; alphabet = A;
Juliana Jaafar CSC 099 Semester 2 2011/2012

36

Arithmetic Operators
Use to manipulate numeric values and perform arithmetic operation Assume ; int a=4, b= 5, d;
C Operation Addition Substraction Multiplication Division Modulus Arithmetic Operator + * / % C Expression d=a+b d=b-2 d=a*b d = a/2 d = b%3 Value of d after assignment 9 3 20 2 2

37

Arithmetic Operators Assignment Operators


Assume ;
int x = 4, y=5, z=8;
Assignment Operator +=
-= *= /= %=

Sample Expression x += 5
y -= x x *= z z /=2 y %=x

Similar Expression x=x+5


y=y-x x = x*z z = z/2 y = y%x

Value of variable after assignment x=9


y=1 x=32 z=4 y=1

38

Arithmetic Operator Increment & Decrement Operator


Operator Called Sample Expression ++a Similar Expression a = a +1 a += 1 ++ postincrement a++ a = a +1 a += 1 -predecrement --a a = a -1 a -= 1 -postdecrement a-a = a -1 Explanation ++ preincrement Increment a by 1, then use the new value of a in expression in which a reside Use the current value of a in the expression which a reside, then increment a by 1 Decrement a by 1, then use the new value of a in expression in which a reside Use the current value of a in the expression which a reside, then decrement a by 1

a -= 1

39

Example : Increment Operator


Statements
int c=5; printf( "%d", ++c ); c=5; printf( "%d", c++ ); int c=5; ++c; printf( "%d", c ); int c=5; c++; printf( "%d", c ); char alphabet = 'D'; alphabet++; printf ("\n%c", alphabet); printf ("\n%c", alphabet++); printf ("\n%c", ++alphabet);

Output

40

Decision Making : Relational & Equality Operator


Assume ; int y=6, x=5;
Relational Operators > < >= <= Sample Expression y>x y<2 x>=3 y<=x Value T (1) F (0) T (1) F (0)

Equality Operators
== !=

Sample Expression
x==5 y!=6

Value
T(1) F(0)
Juliana Jaafar CSC 099 Semester 2 2011/2012

41

Logical Operator
Logical Operators && || ! Called AND OR NOT Sample Operation expression1 && expression 2 expression1 | | expression2 ! expression

Juliana Jaafar CSC 099 Semester 2 2011/2012

42

Example :
Assume;
int x=50;
Sample Expression !(x==60) !(x!=60) Expression 0 (False) 1 (True) !Expression 1 (True) 0 (False)

Juliana Jaafar CSC 099 Semester 2 2011/2012

43

Example : AND (&&)


Assume;
int x=4, y = 5, z=8;
Expression1 Sample Expression Expression2 Expression1 && Expression2 0 (False) 0 (False)

( y > 10) && ( z < =x )

0 (False)

( z < = y) && ( x = = 4) ( y ! = z) && ( z < x ) ( z > = y ) && ( x ! = 3)

0 (False) 1 (True) 1 (True)

1 (True) 0 (False) 1 (True)

0 (False) 0 (False) 1 (True)

44

Example : OR (||)
Assume;
int x = 4, y=5, z=8;
Expression1 Sample Expression Expression2 Expression1 && Expression2 0 (False) 0 (False)

( y > 10) || ( z < =x )

0 (False)

( z < = y) || ( x = = 4) ( y ! = z) || ( z < x ) ( z > = y ) || ( x ! = 3)

0 (False) 1 (True) 1 (True)

1 (True) 0 (False) 1 (True)

1 (True) 1 (True) 1 (True)

45

Operator Precedence
Operators () ++ - - + - ! Associative Left to right Right to left

* / %
+ < <= > >= = = != && || = *= += - = /= %=

Left to right
Left to right Left to right Left to right Left to right Left to right Right to left
Juliana Jaafar CSC 099 Semester 2 2011/2012

46

Example : Operator Precedence


Example 1 int a=10, b=20, c=15, d=8; a*b/(-c*31%13)*d 1. a*b/(-15*31%13)*d 2. a*b/(-15*31%13)*d 3. a*b/(-465%13)*d 4. a*b/(-10)*d 5. 200/(-10)*d 6. -200*d 7. -160 Example 2 int a=15, b=6, c=5, d=4;

d *= ++b a/3 + c
1. d *= ++b a/3+ c 2. d*=7- a/3+c 3. d*=7- 5+c 4. d*=2 + c 5. d*= 7 6. d = d*7 7. d = 28

47

Standard Output & Input Function


Output function printf()
To display information on the computers screen Example :
printf(Programming is great FUN!! Loving IT!);

Input function scanf()


To read data typed from the keyboard Example :
printf(Please enter an integer value >>\n); scanf(%d, val1);

** MUST include <stdio.h> header file

Juliana Jaafar CSC 099 Semester 2 2011/2012

48

Escape Sequence
Indicates that printf() should do something out of the ordinary When encountering a backslash(\) in a string, the compiler looks ahead at the next character and combines it with the backslash to form an escape sequence.

Juliana Jaafar CSC 099 Semester 2 2011/2012

49

Standard Output Function


2 Syntax of printf()
printf(FormatControlString);
Example : printf (Hello Dear, \n);

printf(FormatControlString Format specifier, PrintList);


Example : int year=2006; printf(Year is %d, year);
To read the value of an integer from this variable
Juliana Jaafar CSC 099 Semester 2 2011/2012

Specifier for printing an integer value

50

Common Output Format Specifiers


Specifies the argument type
Data Type int float double char string %d %f %lf %c %s Format Specifiers

Juliana Jaafar CSC 099 Semester 2 2011/2012

51

Example : printf() function


printf( "Sum is %d\n", sum );
%d means decimal integer will be printed sum specifies what integer will be printed

Juliana Jaafar CSC 099 Semester 2 2011/2012

52

Different Ways of Formatting printf()


Display normal message printf("Hello Welcome to C"); Display space printf("\tWelcome"); Display new line printf("\n"); Printing value of variable printf("Addition of two Numbers : %d",sum); Printing value of the calculation printf("Addition of two Numbers : %d", num1+num2);Juliana Jaafar
CSC 099 Semester 2 2011/2012

53

Different Ways of Formatting printf()


Multiple format specifier printf("I Love %c %s",'c',"Programming"); Display integer in different styles
printf(\n%d",1234); printf(\n%3d",1234); printf(\n%6d",1234); printf(\n%-6d",1234); printf(\n%06d",1234);
Output 1234 1234 ##1234 1234## 001234
Juliana Jaafar CSC 099 Semester 2 2011/2012

54

Different Ways of Formatting printf()


Display fraction number in different styles
printf("\n%f",1234.12345); printf("\n%.4f",1234.12345); printf("\n%3.2f",1234.12345); printf("\n%-15.2f",1234.12345); printf("\n%15.2f",1234.12345); Output 1234.123450 //by default, it will print 6 values after the decimal 1234.1235 1234.12 1234.12######## ########1234.12

Juliana Jaafar CSC 099 Semester 2 2011/2012

55

Different Ways of Formatting printf()

char str[]="Programming"; // Length = 11 printf("\n%s",str); // Display Complete String printf("\n%10s",str); // 10 < string Length, thus display Complete String printf("\n%15s",str); // Display Complete String with RIGHT alignment printf("\n%-15s",str); // Display Complete String with LEFT alignment printf("\n%15.5s",str); //Width=15 and show only first 5 characters with RIGHT alignment printf("\n%-15.5s",str); //Width=15 and show only first 5 characters with LEFT alignment Output Programming Programming ####Programming Programming#### ##########Progr Progr########## Juliana Jaafar
CSC 099 Semester 2 2011/2012

Display fraction number in different styles

56

Standard Input Function


Syntax of scanf()
scanf(FormatControlString, InputList); Example: int age;
scanf(%d, &age);

** FormatControlString MUST consist of format


specifiers only ** Each element in InputList must be an ADDRESS to a memory location for which it must be made into ** Address of memory location is specified by prefixing the variable name with an ampersand character (&) address operator
Juliana Jaafar CSC 099 Semester 2 2011/2012

57

Common scanf() Format Specifiers


Data Type int %d Format Specifiers

float
double char string

%f
%lf %c %s

Juliana Jaafar CSC 099 Semester 2 2011/2012

58

Example : scanf() Function


scanf( "%d", &integer1 );
%d - indicates data should be an integer value &integer1 - location in memory to store variable

** When executing the program the user responds to the scanf() statement by typing in a number, then pressing the enter (return) key

Juliana Jaafar CSC 099 Semester 2 2011/2012

59
Juliana Jaafar 2011/2012

Example : scanf() Function


double height; int year; scanf(%lf, &height); scanf(%d, &year); scanf(%lf, height); /* This is an error!! */

Juliana Jaafar CSC 099 Semester 2 2011/2012

60

Example : Inputting Multiple Values with a single scanf()


int height; char ch; double weight; scanf(%d %c %lf, &height, &ch , &weight); Put space between the specifiers ** It is always better to use multiple scanf()s, where each reads a single value
Juliana Jaafar CSC 099 Semester 2 2011/2012

1 /* Fig. 2.5: fig02_05.c 2 Addition program */ 3 #include <stdio.h> 4 5 int main() 6 { 7 int integer1, integer2, sum; declaration */ 8 9 printf( "Enter first integer\n" ); prompt */ 10 scanf( "%d", &integer1 ); an integer */ "Enter second integer\n" ); 11 printf( prompt */ 12 scanf( "%d", &integer2 ); an integer 13 sum = */ integer1 + integer2; assignment of "Sum sum */ 14 printf( is %d\n", sum ); print sum */ 15 16 return 0; /* indicate that program successfully */ 17 } Enter first integer 45 Enter second integer 72 Sum is 117

61
Juliana Jaafar 2011/2012

/*

1. Initialize variables 2. Input

/* /* read /* /* read /* /*

2.1 Sum 3. Print

ended

Program Output

62

Example of C Program
#include <stdio.h> int main() { int num1; scanf(%d,&num1 ); printf(You key in %d\n,num1); return 0; }

Juliana Jaafar CSC 099 Semester 2 2011/2012

63

Structure of a C Program

Juliana Jaafar 2011/2012

Juliana Jaafar CSC 099 Semester 2 2011/2012

Potrebbero piacerti anche