Você está na página 1de 47

CHAPTER 2

FUNDAMENTALS OF C
LEARNING OUTCOMES
After studying this chapter, you should be
able to:
Describe what is data in C programs;
Write variable declarations and
initialization;
Trace a program with multiple expressions;
and
Apply the fundamentals of C in a working
program.
INTRODUCTION
As discussed in Chapter 1, as a programmer,
you need to analyze what a programming
problem requires first before you got to type
out the programming codes.

In this chapter, you will first look at the basic


structure of a C program.

Then, you will learn about the fundamentals


of data types available in C followed by how
to apply them in variables.
STRUCTURE OF A C PROGRAM
Recall from Chapter 1, you have
written a Hello.c program

#include <stdio.h> preprocessor directive

int main() main() program body


{

printf(“Hello World!\n”);

system (“pause”);
return 0; to mark the end of main()
} main()
STRUCTURE OF A C PROGRAM (cont.)

The structure
includes:
preprocessor
directives
global declarations
local definitions
statements

Figure 2.1: Structure of a C Program


STRUCTURE OF A C PROGRAM (cont.)

#include <stdio.h> Calling standard functions


from header files (.h)
#define PI 3.142
int a=5; Declaring program elements
int main() outside main() program
{
int b=10; Defining program elements
printf("Hello World"); inside main() program

Statements in main()
system("pause"); program
return 0;
Will cause the black DOS
} window to be paused until
you press any key (to avoid it
immediately close not giving
you the chance to read what
{ } indicates To mark is printed)
the body of the end of
main() program
program
DATA AND MEMORY CONCEPTS
Variable names such as num1, num2 and
total actually correspond to locations in the
computer’s memory.
Every variable has a name, a type and a
value.
Example:
scanf(“%d”, &num1); //read an integer from keyboard
DATA AND MEMORY CONCEPTS (cont.)
Whenever a value is placed in a memory
location, the value replaces other value
that the location previously had.
int num1 = 20;
scanf(“%d”, &num1); // assume user key in 42
Hence the memory location for num1 will
be:
IDENTIFIERS
 Identifiers are names that you give to data like
variables, constants, functions, types and labels in
your program.
Example 2.1
Mr. M needs to write a C program that will calculate the area of a rectangle. Each
rectangle will have its own length and width. Mr. M will use the formula:
Area = width * length

 Question: How many data can you spot from


Example 2.1?
 Answer: There are three units of data - area, width
and length.

 We know that we will be using the three data or


better said them as identifiers/variables.
VARIABLES DECLARATION
 All data used in a computer must be stored in the
computer’s memory.
 Whenever a name of a data given, it is actually referring
to where it is located in the computer’s memory. In C
programming, it is called a variable.
 Programmer must tell the computer the names of the
variable and clearly define its data type.

The term variable is used because the value stored in the variable
is not fixed (can change).
VARIABLES DECLARATION
 A general form of writing a declaration statement is as
follows:
dataType variableName;

 If a variable holds an integer value, and the name given is


sum, the declaration statement will be like this:
int sum;

 You may also declare multiple variables in a single


declaration.
float mark1, mark2, mark3, sum, average;
VARIABLES INITIALIZATION
 Initialization lets the programmer to decide on the
starting content of the storage location.

 For example, the declaration statement:


int total=20;
declares that variable total is an integer type and sets the
initial value of 20 into the variable.

Initialization is the term used when the first time a value is stored in a
variable, upon declaration.
CONSTANTS
How about when you have to deal with
fixed data values?

For example, government determined tax rate. The tax rate will be
used many times throughout a program. If the tax rate changes,
programmer will be in a trouble to repair the program by changing all
the values initialized in the program. This may cause problems or
errors later on.
CONSTANTS (cont.)
The statement to define the constant is
#define constantName value
It is a standard practice to use all capital
letters to define a constant.
CONSTANTS (cont.)
• You can also declare constant character or
string like this:

Single character: #define ALPHABET ‘A’

String : #define WORD “IIUM”


BASIC GUIDELINES ON NAMING DATA

Actually, we do not really need to be very


rigid in giving names to identifiers in our C
program.
However, we still need to refer to some set
of rules in providing names to identifiers.
Rule # Descriptions Good Examples Bad Examples
1 Do not use C int number1; int printf;
keywords float sum; float gets;
 printf() and gets() are two reserved words, therefore they must not
be used in variable names
2 Variable name float age; float 20age;
must not start
with numbers
3 The name given char char name_of_students_in_a_single_classroom_at CFS[20];
must not be too student_name[20];  this is a meaningful name, but too long and increases the risk of
long having more syntax errors
4 Do not use int total_num; int total-num;
special character double double total*weight;
or blank space in total_weight;  both are invalid because contain special characters hyphen (-) and
between the asterisk (*)
words for int total number;
variable names  invalid because contains a blank space
5 C is case int no1, no2; int no, NO;
sensitive.  C will treat these two variables as two different identifiers
Therefore,  May cause confusion
uppercases and
lowercases are
significant.
6 Provide float width; float w;
appropriate and  width of a  ‘w’ can be anything, ‘w’ can be wind, water, west etc. This is valid,
meaningful rectangle but poorly written.
names
Table 2.1: Rules for Naming Identifiers
EXERCISE 2.1
(page 30 & 31)
DATA TYPES
 Data type will determine what data can be stored in a
certain storage location, number of bytes allocated to
it and how the data operates.

 Common Data Types in C:


Void (void)
Integer (int)
Floating points (float , double)
Character (char)
# C Data Amount of Description Example
type storage
1 Void None  The type of data that have no value. void display();
(void)  There are cases where no data Explanation: The user-defined function display() will
stored or required by the program. return nothing, since the front data type is void.
2 Integer 4 Bytes  To represents numerical value int num = 20;
(int) ranging between -2,147,483, 648 to Explanation: In memory, num is reserved for storing an
+2,147,483, 647. integer value only.
3 Floating float  This category of data types is To initialize a width of a small rectangle that have 2.54cm,
points (4 Bytes) specifically used for floating point we use:
(float , double numbers. float width = 2.54;
double) (8 Bytes)  The storage size for double is However, to declare the distance in between two towns, we
much bigger as compared to will use:
float. double distance = 987980.99;
 float is used for single precision
and double for double precision.
4 Character 1 Byte for each  Character is the type that Single Character
(char) character representing non-numeric data char status = ’A’;
 There are two categories of String
character data: Single character and A combination of characters will form a string (Example:
string. “good”).
In declaration, we use:
char name[10] = ”good”;
 Note that, single character can only fit 1 character;
however string can fit many characters as specified in
the square brackets. They are also called as character
arrays.
 Further details on strings will be discussed in Chapter
6.
Table 2.2: Common Data Types in C
EXPRESSIONS IN C
Arithmetic
Precedence and Associativity
Implicit and Explicit Conversions
Unary Operators in Postfix & Prefix
Expressions
Compound Expression
ARITHMETIC IN C
Arithmetic Algebraic C Example
Operation Expression Expression
Addition M +9 M +9 int m=20, ans;
+ ans = m+9;
The value of ans is 29. (20+9 = 29)

Subtraction M–9 M-9 int m=20, ans;


- ans = m-9;
The value of ans is 11. (20-9 = 11)

Multiplication QxW Q*W int W=20, Q=2, ans;


* ans = Q*W;
The value of ans is 40. (2*20 = 40)

Division x/y int x=20, y=10, ans;


/ x ans = x/y;
y
The value of ans is 2. (20/10 = 2)

Modulo R mod S R%S int R=9, S=2, ans;


(Remainder) ans = R%S;
% The value of ans is 1. (9 % 2 = 1)

Table 2.3: Arithmetic Operators


PRECEDENCE AND ASSOCIATIVITY
• Precedence rule is used when we have
different level of operators in C expressions.
• The calculations of multiplication, division and
modulo are evaluated first before addition
and subtraction.
• Associativity rule is used (evaluated either
left-to-right or right-to-left) when we have
multiple operators of the same precedence
level.
PRECEDENCE AND ASSOCIATIVITY
(cont.)

Observe the outputs:


IMPLICIT AND EXPLICIT CONVERSIONS
We use implicit and explicit conversions
when we have different data types in C
expression.
One of the data types must be converted
either to lower or higher level (promote or
demote).

Table 2.5: Conversion Rank of Data Types


IMPLICIT AND EXPLICIT CONVERSIONS
(cont.)
To cast data from one data type to another,
type the new data type in parentheses
before the value to be converted.
Unary Operators in Postfix
& Prefix Expressions
If a variable m is incremented by 1, the
increment operator ++ can be used:
instead of writing it as m=m+1, we may
write it as m++.

m++ has the same effect as m=m+1


POSTFIX EXPRESSIONS
In postfix expressions, the original value is
being used and result will be modified
later.

Figure 2.4: Result of Postfix A++


PREFIX EXPRESSIONS
In prefix expressions, the result will be
modified immediately.

Figure 2.5: Result of Prefix ++A


# Postfix Prefix

1 int num = 2; int num = 2;


num++; ++num;
printf("%d", num); printf("%d", num);
Output : 3 Output : 3

2 int num = 2; int num = 2;


num++; ++num;
printf("%d", num++); printf("%d", ++num);
Output : 3 Output : 4

3 int num = 2; int num = 2;


num++; ++num;
num = num++ + 2; num = ++num + 2;
printf("%d", num); printf("%d", num);
Output : 6 Output : 6

4 int num = 2; int num = 2;


int count = 0; int count = 0;
num++; ++num;
count = num++ + 2; count = ++num + 2;
printf("Count %d\n", count); printf("Count %d\n", count);
printf("Num %d\n", num); printf("Num %d\n", num);
Output : Count 5 Output : Count 6
Num 4 Num 4

Table 2.6: Postfix and Prefix Examples


COMPOUND EXPRESSIONS
C provides several assignment operators
for abbreviating assignment expressions.

Table 2.7: Expansion of Compound Expressions


EXERCISE 2.2
(page 41 & 42)
MANAGING INPUT AND OUTPUT
The printf()statement is used to display an
output.
 Pass at least two items to printf():
control message
data list (value to be displayed)
Items passed to a function are always
placed within parentheses and are called
arguments.
MANAGING INPUT AND OUTPUT
(cont.)
Conversion control sequence:
Has a special meaning to tell the function what
type of values is to be displayed and how to
display them.
Also referred to as conversion specification or
format specifiers.

Table 2.8: List of Conversion Control Sequence


The following are more examples on how we
can format our output by using flags in the
printf( ) Format Control String.
MANAGING INPUT AND OUTPUT
(cont.)
Minimum field width can be specified to
the data type that we are going to display.
MANAGING INPUT AND OUTPUT
(cont.)
Precision specification
If you do not specify its value, by default the
output for floating-point numbers will be
printed with six decimal places.

printf(“%f”, 1.5); Output: 1.500000


printf(“%.2f”, 1.5); Output: 1.50
MANAGING INPUT AND OUTPUT
(cont.)
The scanf() statement
Allows the user to enter a value.
Then value then stored directly in the variable.

Requires a control string as the first argument. The


control string will tell functions the type of data
being input.
MANAGING INPUT AND OUTPUT
(cont.)
A sample statement that uses scanf()
function is:
scanf(“%d”, &mark);
Note that, when using scanf(), the
address operator ‘&’ must be used for all
data type except string. Hence an input to
a string will be handled as:
scanf(“%s”, name);
Sample program:

 The first call to printf() produces a prompt message asking input from
user.
 The scanf() function hold the computer temporarily while user type a
value. By hitting ENTER key, user is actually sending signal to computer to
proceed to the next operation.
MANAGING INPUT AND OUTPUT
(cont.)
COMMENTS
 To describe your codes or to make it easier for other
programmers in understanding your codes later.
 You can put comments anywhere in your programs (make
sure they are meaningful).
 Use /* */ or // symbols.
ESCAPE SEQUENCES
A combination of backslash (\) and a
specific character will result in different
effects to the program.
Normal actions by the character will be
ignored once backslash is used.
EXERCISE 2.3
(page 49-53)
SUMMARY
At this point, you have learned the
Fundamentals of C Programming. The
following are discussed earlier in this
chapter:

Basic data types and how to name variables


and constants;
Arithmetic Operations in C;
Evaluations of C expressions;
Formatting Input & Output for a C program.
PROGRAMMING
PROBLEMS
(page 53-56)

Você também pode gostar