programming chapter 1 week 2
TRANSCRIPT
-
8/13/2019 Programming Chapter 1 Week 2
1/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 1
1.2VariablesandConstants
1.2 Variables and Constants
Two categories of data
Variable - the value can be changed during program execution
Constants - the value is fixed
DataData
Each variable has:1. Name
2. Type
3. Holds a valuethat you assign to them
VariablesVariables
-
8/13/2019 Programming Chapter 1 Week 2
2/34
-
8/13/2019 Programming Chapter 1 Week 2
3/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 3
HINT:
Give your variable names that help describe the values they
are holding.
A studentname _counter firstName
a student_name SUKOM1998 secondName
x1 StudentName sukom_98 value1st
x2 SALARY Main value2nd
Valid Variable NamesValid Variable Names
main 2NDperson student name
printf employee name class code
int
question?
Invalid Variable Names: Why ?Invalid Variable Names
Note:
Uppercase andlowercase aredifferent.
-
8/13/2019 Programming Chapter 1 Week 2
4/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 4
Note (*):C view a strings as a collection of characters.
We define string type based on char data type.
Example: char MyName[15];
Variable Types
Character
Integer
Floating-point number
String
char , unsigned char,signed char
int , unsigned int, signedint, long, short int,unsigned short int
float , double, long double * No strings type in C
Variable TypesVariable Types
Divided into four (4) main
subcategories:
-
8/13/2019 Programming Chapter 1 Week 2
5/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 5
Data Range
Note:
Each
variable typehas it own
minimum
and
maximum
size the data
that its can
handle.
VariableType Minimum Maximum
char
unsigned char
signed char
int
unsigned int
signed int
short int
unsigned short int
signed short int
long int
signed long intfloat
double
long double
-128
0
-128
-32768
0
-32768-32768
0
-32768
-2147483648
-2147483648-3.4E+38
-1.7E+308
-1.7E+308
127
255
127
32767
65535
3276732767
65535
32767
2147483647
21474836473.4E+38
1.7E+308
1.7E+308
-
8/13/2019 Programming Chapter 1 Week 2
6/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 6
Syntax:
DataType VariableName;
Two main categories:
Global Variables
Local Variables
#include
/*global declarations*/main( ){/*local declarations*/
clrscr();
printf();:
}
DeclarationVariable DeclarationsVariable Declarations
Referred asvari able scope
-
8/13/2019 Programming Chapter 1 Week 2
7/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 7
/* Program to show variable declaration*/
#include
/* Global declaraion*/
intlength;floatbalance;
main(){/* Local declaration */
charfirstInitial;:
}
Two global
variables
One local
variables
Declare variable only if you
want to use it to handle the
data.
Each variable type require
different memory space. You can declare your
variables as local or global.
Global/Local Variable
Example of Variable DeclarationsExample of Variables Declarations
-
8/13/2019 Programming Chapter 1 Week 2
8/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 8
/* Program to show variable declaration*/#include/* Global variable */
intlength;floatbalance;
main(){/* Global variable */
charFirstInitial;:}
Computer will allocate enough
spaceto handle the data from
that type.
length
balance
FirstInitial
2 bytes
4 bytes
1 byte
Memory Allocation
What happen to variable declaration ?What happen to variable declaration
RAM
Different compiler/computer may require differentsize of memory for each data type.
-
8/13/2019 Programming Chapter 1 Week 2
9/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 9
Integer-1, 0, 1, 12, 15
Floating-point number
-1.5, 1.0, 3.14
Character
A, B, , 1, 2, , ?, *, $Strings
Management and Science University
Shah Alam
ConstantsConstantsConstants
I nteger constants
Floating-point
constants
Character constants
Str ing constants
?What does each of the followingmeans (constant or variable).
If constant, from what type ?
A A A
-
8/13/2019 Programming Chapter 1 Week 2
10/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 10
ConstantsCharacter ConstantsCharacter Constants A character constantis a single character, enclosed in single quotation
marks.
Character constantshave integer valuesthat are determined by the
computers particular character set.
ASCII character set
ASCII:American Standard Code for Information Interchange
int code = 65;
printf(Code = %d, code);printf(Code = %c, code);
char code = Z;
printf(Code = %c, code);
printf(Code = %d, code);
Example:
Trace the output of both C codesbased on ASCII Character Set.
-
8/13/2019 Programming Chapter 1 Week 2
11/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 11
Example:
Usingcombination
of ASCIIcharacters todraw a box.
/* DRAW A BOX */
printf(%c, 201); /* left top character */for(x=1;x
-
8/13/2019 Programming Chapter 1 Week 2
12/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 12
Escape Sequence
Certain nonprinting characters, as well as the backslash (/) and the
apostrophe (), can be expressed in terms of escape sequences.
Character Escape ASCII
Sequence Value
bell (alert) \a 007
backspace \b 008
horizontal tab \t
009vertical tab \v 011
new line (line feed) \n 010
form feed \f 012
carriage return \r 013
quotation mark () \ 034
apostrophe() \ 039question mark (?) \? 063
backslash (\) \\ 092
null \0 000
Shown below are several
character constants,
expressed in terms of
escape sequences.
\n \t \b
\\ \ \
Note:
printf(\HELLO\);will printHELLOon screen.
printf("\007Attention, that was a beep!\n");
-
8/13/2019 Programming Chapter 1 Week 2
13/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 13
A variable holds a value that you assign them using anassignment statement.
Syntax:
var iableName = Expression ;
Assigning Value to VariablesAssigning Values to Variables
main(){/* Local declaration */
intcount;
/* assign a value to a variable */count = 3;:
}
count
count3
RAM
Refer to 1.5
-
8/13/2019 Programming Chapter 1 Week 2
14/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 14
Note:
String is a collection of characters to represents a Name (mother, father,
student, employee, car, building, shopping complex, software, ...), Address, etc
Two methods:
1. Array of characters
2. Character pointers
The base type is char.
C view a strings as a
collection of characters.
StringsHow to define strings data typeHow to define string data type
1.3CharacterArraysandStrings
1.3 Character Arrays and Strings
Array of characters
Syntax:
char VariableName[STRING_LENGTH];Note:
STRING_LENGTHisan integer constant.
-
8/13/2019 Programming Chapter 1 Week 2
15/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 15
String VariableExample:char YourName[10];
String:Declared as an
array of character with
maximum length of
values 9 characters (One
space will be use by
NULL ZERO to indicate
the end of string).
Memory
Representation:
YourName[0]
YourName[1]
YourName[2]
YourName[3]
YourName[4]
YourName[5]
YourName[6]
YourName[7]
YourName[8]
YourName[9]
Each memoryslot represent acharacter
-
8/13/2019 Programming Chapter 1 Week 2
16/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 16
Strings
representation
Example:
You will use the name without
number in bracket to input a
string value using scanf()or
gets() function:
/* prompt the user */printf(Enter your name :);
scanf(%s, YourName);
OR
gets(YourName);
IFthe input is Abdullah
MemoryRepresentation:
YourName[0]
YourName[1]
YourName[2]
YourName[3]
YourName[4]
YourName[5]
YourName[6]
YourName[7]
YourName[8]
YourName[9]
9 spaces are
required tohandle thestring
Abdullah
A
b
d
u
l
l
a
h
\0
Note: To print the string, you dont have to refer individual
characters. Print as a string:
printf(Your name: %s, YourName);
-
8/13/2019 Programming Chapter 1 Week 2
17/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 17
H
E
L
L
O
\0
Example:
The string constant HELLO contains 6characters.
The length is 5.
When we put it as an argumentin printf()
printf( HELLO );
We will see
HELLO
displayed on screen.
In computer
memory
Null Zero
Used to indicate
end-of-string
String
length
Strings in memory
String constant as an argumentto printf() function
RAM
-
8/13/2019 Programming Chapter 1 Week 2
18/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 18
1.4PreprocessorDirectives
1.4 Preprocessor Directives
There ate two main preprocessor directives:
#include - Include header file(s)
#define - Define symbolic constant(s) or macros
#include#include
Merges a disk file into your source program
Syntax:
#include
or
#include FileName
-
8/13/2019 Programming Chapter 1 Week 2
19/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 19
Tell the processor to look the include file in adefault includedirectory ( c:\tc\include>); set up by your compiler.
Example: #include
include#include
Tell the processor first to look for the include file in the
directory where the source code is stored and, if missing,
the to look for it in the systems include directory.
Example: #include prototype.h
#include FileName
ASCII text file
-
8/13/2019 Programming Chapter 1 Week 2
20/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 20
#define#define
It does nothing more than a search-and-replacecommand on aword processor.
Syntax:
#define argument1 argument2
#include
#define MAX 5/* symbo lic cons tan t defin it ion */:
printf(Max data is %d, MAX);Replaced with 5
define
Symbolic Constant
Example :
Defines a symbolic constant
-
8/13/2019 Programming Chapter 1 Week 2
21/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 21
#defineTRUE 1
#defineFALSE 0
#defineNULL 0
#defineAND &&
#defineOR ||#defineNOTEQUAL !=
:
game_over = FALSE;
while( game_over NOTEQUAL TRUE) {
:
}
:
The definestatement is used to make programs more readable. Consider
the following examples,
In general, preprocessor constants are written in UPPERCASE.
The Program:
game_over != 1
The meaning:
-
8/13/2019 Programming Chapter 1 Week 2
22/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 22
Macros
Macros are inline code which are substituted at compile time. The definitionof a macro, which accepts an argument when referenced,
#define SQUARE(x) (x)*(x)
y = SQUARE(v);
In this case, vis equated withxin the macro definition ofsquare, so the
variableyis assigned the square of v. The brackets in the macro definition
ofsquareare necessary for correct evaluation. The expansion of the macro
becomes
y = (v) * (v);
Defines a macro
The Program:
-
8/13/2019 Programming Chapter 1 Week 2
23/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 23
Macros
Naturally, macro definitions can also contain other macro definitions,
#define AREA(x) (x)*(x)
#define RECTANGLE(x) AREA(x)
#define TRIANGLE(x) ((0.5)*AREA(x))
#define CUBE(x) (x)*(AREA(x))
The Program:
-
8/13/2019 Programming Chapter 1 Week 2
24/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 24
Two method
Assignment statement
Input Functions
Input/Output
1.5InputandOutput
1.5 Input and Output
Assigning Value to VariableAssigning Value to Variable
Assignment StatementAssignment Statement
Syntax:
variableName = Expression;
Can be: another variable, constantor
combination of both.
-
8/13/2019 Programming Chapter 1 Week 2
25/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 25
Example ofassignment statements:
Nett salary:
Area of a rectangle:
Volume of a cube:Area of a circle:
Linear graph:
Average of two numbers:
Sum of two numbers:
Current number of studentsis 30
Value of myAge is equals
to value ofyourAge
NettSalary =BasicSalary - (EPF+SOCSO);
AreaOfRectangle= 0.5 * length * width;
VolumeOfCube= length * width * depth;AreaOfCircle= 3.142 * pow(radius, 2);
y= (2 * x) + 3;
average= (first + second) / 2.0;
sum= value1st + value2nd;
currentStudent= 30;
myAge=yourAge;
Syntax: variableName = Expression;
FORMULA:
-
8/13/2019 Programming Chapter 1 Week 2
26/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 26
#include
int v, w, x = 1; /* 2 global variables */
main()
{ float y=2.5, z; /* 2 local variables */
v = x;
w = v + 2;
z = 3.7;
printf(w = %d x = %d\n, w, x);
printf(y = %.2f z = %.2f\n, y, z);
}
Exampleof
program:
intv, w, x = 1; /* 2 global variables */
float y=2.5, z; /* 2 local variables */
v = x;
w = v + 2;
z = 3.7;
v
w
x
y
z
1
3
1
2.5
3.7
Assignment during
declaration
RAM
-
8/13/2019 Programming Chapter 1 Week 2
27/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 27
Input FunctionsInput Functions
Use the scanf() function from stdio.h.Syntax:
scanf(CC, &Variable);CC: Conversion Characters
%c character
%s string%d integer%f float
&: The address of variable
No need for string type.
Example:/* input using scanf() */
scanf(%c, &a);scanf(%s, b);
scanf(%d, &c);
scanf(%f, &d);
/* variable declarations */
char a;char b[10];
int c;
float d;
Input Function
-
8/13/2019 Programming Chapter 1 Week 2
28/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 28
#include
main(){ char fullName[35];
/* Label each of your input */
printf(Please enter your full name :);
scanf(%s, fullName);
printf(Your name is %s, fullName);
}
You can also simply use the gets();
gets(fullName);
Example:
Note:
Your maximum
length of name is
34 characters; not
35 characters.
Differentiate the use of scanf()and gets()to input string value.
-
8/13/2019 Programming Chapter 1 Week 2
29/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 29
Output FunctionsOutput Functions Use the printf() function from stdio.h.
Syntax:
printf(CS, Variables);CS: Control String -Combination of string and
Conversion Character
/* variable declarations */
int age;
/* input */
printf(Please enter your age ? );
scanf(%d, &age);
/* output*/
printf(Your age is%dyears.,
age);
Example:
Output Function
-
8/13/2019 Programming Chapter 1 Week 2
30/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 30
(A) Determine, as best you can, the purpose of each of the following C
programs. Identify all variables, input and output statements, assignment
statements, and any other special features that you recognize.
#include main()
{
printf(Welcome to the World of Computing !\n);}
#include #define MESSAGE \aWelcome to the World of Computing !\n
main()
{
printf(MESSAGE);}
Exercise
-
8/13/2019 Programming Chapter 1 Week 2
31/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 31
#include
main()
{
float base, height, area;printf(Base :);
scanf(%f, &base);
printf(Height :);
scanf(%f, &height);
area = (base * height) / 2.;
printf(Area: %f, area);
}
-
8/13/2019 Programming Chapter 1 Week 2
32/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 32
(B) Write a program that accepts your full name, address,height (meter),
weight (kilogram) and ages (years) from keyboards. Then redisplay all
accepted data onto computer screen using appropriate format.
HINTS:
Redisplay the data as registration form.
If the compiler complaint that your program has an error(s), read the
highlight statements at message windows to assist you correct the error.
(C) Find the library functionsthat gets the system date and time.
What header files that declare it.
-
8/13/2019 Programming Chapter 1 Week 2
33/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 33
(D) Explain the purpose of each library functions listed below.
Named the header file that it belongs to.
Find or write a simple program to show how to use it.
strlen()
strcpy()
strcat()
strupr()
strlwr()
strcmp()
getch()
getche()
tolower()
toupper()
fopen()fclose()
fscanf()
fprintf()
sqrt()
pow()
atoi()
itoa()
gotoxy()
textcolor()
textbackground()
gettime()
getdate()random()
-
8/13/2019 Programming Chapter 1 Week 2
34/34
FCS 0084 Programming Chapter 1
Introduction to C Week 2
Management and Science University 34
Printf is also known as cout