Вы находитесь на странице: 1из 34

FCS 0084 Programming Chapter 1

Introduction to C Week 2

Management and Science University
1
1 . 2 V a r i a b l e s a n d C o n s t a n t s



1.2 Variables and Constants




Two categories of data

Variable - the value can be changed during program execution

Constants - the value is fixed
Data
Data

Each variable has:
1. Name
2. Type
3. Holds a value that you assign to them
Variables
Variables
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
2
Must begin with a letter of the alphabet but, after the first letter, they can
contain:

Min length: 1 character
Max length: 31 characters (depends on compiler)
Variable Name
Naming Variables
Naming Variables
Variables Length
Variables Length
1. Letters: A...Z, a...z
2. Numbers: 0...9
3. Underscore character: _
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 Names
Valid Variable Names
main 2NDperson student name
printf employee name class code
int
question?
Invalid Variable Names: Why ?
Invalid Variable Names
Note:
Uppercase and
lowercase are
different.
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

O Character
O Integer
O Floating-point number
O String
char , unsigned char,
signed char
int , unsigned int, signed
int, long, short int,
unsigned short int
float , double, long double
* No strings type in C
Variable Types
Variable Types
Divided into four (4) main
subcategories:
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
5
Data Range
Note:
Each
variable type
has 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 int
float
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
32767
32767
65535
32767
2147483647
2147483647
3.4E+38
1.7E+308
1.7E+308
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
6
Syntax:
DataType VariableName;

Two main categories:
O Global Variables
O Local Variables



#include <stdio.h>

/*global declarations*/
main( )
{
/*local declarations*/
clrscr();
printf();
:
}
Declaration
Variable Declarations
Variable Declarations

Referred as
variable scope

FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
7

/* Program to show variable declaration*/
#include <stdio.h>

/* Global declaraion*/
int length;
float balance;

main()
{
/* Local declaration */
char firstInitial;
:
}

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 Declarations
Example of Variables Declarations
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
8

/* Program to show variable declaration*/
#include <stdio.h>
/* Global variable */
int length;
float balance;

main()
{
/* Global variable */
char FirstInitial;
:
}

Computer will allocate enough
space to 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 different
size of memory for each data type.
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
Constants
Constants
Constants
I nteger constants
Floating-point
constants
Character constants
String constants
? What does each of the following
means (constant or variable).
If constant, from what type ?
A A A
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
10
Constants
Character Constants
Character Constants
A character constant is a single character, enclosed in single quotation
marks.
Character constants have integer values that 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 codes
based on ASCII Character Set.
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
11
Example:
Using
combination
of ASCII
characters to
draw a box.

/* DRAW A BOX */
printf(%c, 201); /* left top character */
for(x=1;x<=5; x++) printf(%c, 205);
printf(%c\n, 187); /* right top character */

/* vertical left/right sides */
for(x=1;x<=5; x++) printf(%c %c\n, 186, 186);

printf(%c, 200); /* left bottom character */
for(x=1;x<=5; x++) printf(%c, 205);
printf(%c, 188); /* right bottom character */


ASCII Character

The Program:


Assignment:
Draw boxes shown below using combination of ASCII characters.
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 009
vertical tab \v 011
new line (line feed) \n 010
form feed \f 012
carriage return \r 013
quotation mark () \ 034
apostrophe() \ 039
question 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 print HELLO on screen.
printf("\007Attention, that was a beep!\n");
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 an
assignment statement.

Syntax:
variableName =Expression;
Assigning Value to Variables
Assigning Values to Variables

main()
{
/* Local declaration */
int count;
/* assign a value to a variable */
count = 3;
:
}

count
count
3
RAM
Refer to 1.5
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.
Strings
How to define strings data type
How to define string data type
1 . 3 C h a r a c t e r A r r a y s a n d S t r i n g s



1.3 Character Arrays and Strings


Array of characters
Syntax:
char VariableName[STRING_LENGTH];
Note:
STRING_LENGTH is
an integer constant.
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
15
String Variable
Example:
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 memory
slot represent a
character
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);

IF the input is Abdullah




Memory
Representation:
YourName[0]
YourName[1]
YourName[2]
YourName[3]
YourName[4]
YourName[5]
YourName[6]
YourName[7]
YourName[8]
YourName[9]
9 spaces are
required to
handle the
string
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);

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 6
characters.
The length is 5.
When we put it as an argument in 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 argument
to printf() function
RAM
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
18
1 . 4 P r e p r o c e s s o r D i r e c t i v e s



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 <FileName>
or
#include FileName




FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
19
Tell the processor to look the include file in a default include
directory ( c:\tc\include> ); set up by your compiler.

Example: #include <stdio.h>





include
#include <FileName>
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
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-replace command on a
word processor.

Syntax:
#define argument
1
argument
2



#include <stdio.h>
#define MAX 5 /* symbolic constant definition */
:
printf(Max data is %d, MAX);



Replaced with 5
define
Symbolic Constant
Example :

Defines a symbolic constant
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
21
#define TRUE 1
#define FALSE 0
#define NULL 0
#define AND &&
#define OR ||
#define NOTEQUAL !=
:
game_over = FALSE;
while( game_over NOTEQUAL TRUE ) {
:
}
:

The define statement 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:
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 definition
of a macro, which accepts an argument when referenced,

#define SQUARE(x) (x)*(x)

y = SQUARE(v);

In this case, v is equated with x in the macro definition of square, so the
variable y is assigned the square of v. The brackets in the macro definition
of square are necessary for correct evaluation. The expansion of the macro
becomes

y = (v) * (v);



Defines a macro

The Program:

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:

FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
24
Two method
O Assignment statement
O Input Functions
Input/Output
1 . 5 I n p u t a n d O u t p u t



1.5 Input and Output



Assigning Value to Variable
Assigning Value to Variable
Assignment Statement
Assignment Statement
Syntax:
variableName =Expression;
Can be: another variable, constant or
combination of both.
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
25
Example of
assignment statements:


O Nett salary:
O Area of a rectangle:
O Volume of a cube:
O Area of a circle:
O Linear graph:
O Average of two numbers:
O Sum of two numbers:
O Current number of students
is 30
O Value of myAge is equals
to value of yourAge


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:
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
26

#include <stdio.h>

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:
int v, 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
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
27
Input Functions
Input 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
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
28
#include <stdio.h>
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.
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
29
Output Functions
Output 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 %d years.,
age);
Example:
Output Function
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 <stdio.h>
main()
{
printf(Welcome to the World of Computing !\n);
}
O
#include <stdio.h>
#define MESSAGE \aWelcome to the World of Computing !\n
main()
{
printf(MESSAGE);
}
O
Exercise
FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
31
O
#include <stdio.h>
main()
{
float base, height, area;
printf(Base :);
scanf(%f, &base);
printf(Height :);
scanf(%f, &height);

area = (base * height) / 2.;

printf(Area: %f, area);
}
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 functions that gets the system date and time.
What header files that declare it.
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()


FCS 0084 Programming Chapter 1
Introduction to C Week 2

Management and Science University
34
Printf is also known as cout<<

Вам также может понравиться