Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
Example of C Program
Output of C program
output
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
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
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*/
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;
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
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
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
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
Invalid Identifiers
$sum // $ is illegal 2names // cant start with 2 stdnt Nmbr // cant have space int // reserved word
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
long int
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)
24
25
26
Floating point
Numbers that have decimal point Example : 23.7, 189.0231 and 0.987
27
The size of variable is the number of bytes of memory it uses. (> varible > range can hold)
28
short int unsigned short int int unsigned int long int
unsigned long int
2 2 2 2 4
4
Maximum Value
-32,768 0 -2,147,483,648
0
29
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
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
35
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
Sample Expression x += 5
y -= x x *= z z /=2 y %=x
38
a -= 1
39
Output
40
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
42
Example :
Assume;
int x=50;
Sample Expression !(x==60) !(x!=60) Expression 0 (False) 1 (True) !Expression 1 (True) 0 (False)
43
0 (False)
44
Example : OR (||)
Assume;
int x = 4, y=5, z=8;
Expression1 Sample Expression Expression2 Expression1 && Expression2 0 (False) 0 (False)
0 (False)
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
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
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.
49
50
51
52
53
54
55
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
56
57
float
double char string
%f
%lf %c %s
58
** When executing the program the user responds to the scanf() statement by typing in a number, then pressing the enter (return) key
59
Juliana Jaafar 2011/2012
60
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
/*
/* /* read /* /* read /* /*
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; }
63
Structure of a C Program