Transcript Document

BIL104E: Introduction to Scientific and
Engineering Computing, Spring 2005.
Lecture 2
Outline
2.1
2.2
Introduction
Basics of C Programs
• Constants and Variables
• Expressions
• Statements and Statement blocks
• C function types and names
• Arguments to functions
• The body of a function and Function calls
2.3
2.4
2.5
Another Simple C Program: Adding Two Integers
Memory Concepts
Data Types
• int
• float
• char
2.6
2.7
Arithmetic in C
Keywords in C
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 1
2.2 The Basics of the C Program
Before we go into detail of C programming Language Syntax
let us look at the basic definitions:
• Constants and variables
• Expressions
• Statements
• Statement blocks
• C function types and names
• Arguments to functions
• The body of a function
• Function calls
Fall 2003, Gülcihan Özdemir Dağ
Lecture 2: page 2
The Basics of the C Program
• As a building is made of bricks, a C program is made of basic
elements, such as expressions, statements, statement blocks,
and function blocks.
• But first, you need to learn two smaller but important elements,
constant and variable, which make up expressions.
• Constants and Variables :
– As its name implies, a constant is a value that never changes. A variable,
on the other hand, can be used to present different values.
• Expressions
– An expression is a combination of constants, variables, and operators
that are used to denote computations. For instance, the following:
– (2 + 3) * 10 is an expression that adds 2 and 3 first, and then multiplies
the result of the addition by 10. (The final result of the expression is 50.)
– Similarly, the expression 10 * (4 + 5) yields 90. The 80/4 expression
results in 20.
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 3
The Basics of the C Program
• Expression Description
–
–
–
–
6
i
6+i
Exit(0)
 An expression of a constant.
 An expression of a variable.
 An expression of a constant plus a variable.
 An expression of a function call.
• Arithmetic Operators
As you've seen, an expression can contain symbols such as +, *, and /. In the
C language, these symbols are called arithmetic operators.
Symbol
Meaning
+
Addition
Subtraction
*
Multiplication
/
Division
%
Remainder (or modulus)
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 4
The Basics of the C Program
• Among the arithmetic operators, the multiplication, division, and remainder
operators have a higher precedence than the addition and subtraction
operators. For example, the expression
2 + 3 * 10 yields 32, not 50.
Because of the higher precedence of the multiplication operator, 3 * 10 is
calculated first, and then 2 is added into the result of the multiplication.
• As you might know, you can put parentheses around an addition (or
subtraction) to force the addition (or subtraction) to be performed before a
multiplication, division, or modulus computation. For instance, the
expression
(2 + 3) * 10
performs the addition of 2 and 3 first before it does the
multiplication of 10.
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 5
The Basics of the C Program
• Statements
– In the C language, a statement is a complete instruction, ending with a
semicolon. In many cases, you can turn an expression into a statement by
simply adding a semicolon at the end of the expression.
– For instance, the following
i = 1; is a statement.
You may have already figured out that the statement consists of an
expression of i = 1 and a semicolon (;).
Here are some other examples of statements:
i = (2 + 3) * 10;
i = 2 + 3 * 10;
j = 6 % 4;
k = i + j;
Also, below are C statements.
return 0;
exit(0);
printf ("Howdy, neighbor! This is my first C program.\n");
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 6
The Basics of the C Program
• Statement Blocks
– A group of statements can form a statement block that starts with an opening
brace ({) and ends with a closing brace (}). A statement block is treated as a
single statement by the C compiler.
– For instance, the following
for(. . .) {
s3 = s1 + s2;
mul = s3 * c;
remainder = sum % c;
}
is a statement block that starts with { and ends with }
• Anatomy of a C Function
Functions are the building blocks of C programs. Besides the standard C
library functions, you can also use some other functions made by you or
another programmer in your C program. In Hour 2 you saw the main()
function, as well as two C library functions, printf() and exit(). Now, let's
have a closer look at functions.
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 7
Function’s Anatomy
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 8
The Basics of the C Program
• Giving a Function a Valid Name
– A function name is given in such a way that it reflects what the function
can do. For instance, the name of the printf() function means "print
formatted data."
– There are certain rules you have to follow to make a valid function
name. The following are examples of illegal function names in C:
– Illegal Name
2 (digit)
* (Asterisk)
+ (Addition)
. (dot)
total-number
account'97
Spring 2005, Gülcihan Özdemir Dağ
The Rule
A function name cannot start with a digit.
A function name cannot start with an asterisk.
A function name cannot start with one of the
arithmetic signs that are reserved C keywords.
A function name cannot start with ..
A function name cannot contain a minus sign.
A function name cannot contain an apostrophe.
Lecture 2: page 9
The Basics of the C Program
•
Arguments to C Functions
– You often need to pass a function some information before executing it. For example, in
first program, “Hello World.\n", is passed to the printf() function, and then printf() prints
the string on the screen.
– Pieces of information passed to functions are known as arguments. The argument of a
function is placed between the parentheses that immediately follow the function name.
– The number of arguments to a function is determined by the task of the function. If a
function needs more than one argument, arguments passed to the function must be
separated by commas; these arguments are considered an argument list.
– If no information needs to be passed to a function, you just leave the argument field
between the parentheses blank.
•
The Beginning and End of a Function
– As you may have already figured out, braces are used to mark the beginning and end of a
function. The opening brace ({) signifies the start of a function body, while the closing
brace (}) marks the end of the function body.
– As mentioned earlier, the braces are also used to mark the beginning and end of a
statement block. You can think of it as a natural extension to use braces with functions
because a function body can contain several statements.
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 10
The Basics of the C Program
• The Function Body
– The function body in a function is the place that contains variable
declarations and C statements. The task of a function is accomplished by
executing the statements inside the function body one at a time.
– Listing below demonstrates a function that adds two integers specified
by its argument and returns the result of the addition.
• Listing: A function that adds two integers.
/* This function adds two integers and returns the result */
int integer_add( int x, int y ) {
int result;
result = x + y;
return result;
}
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 11
The Basics of the C Program
#include <stdio.h>
/* This function adds two integers and returns the result */
int integer_add( int x, int y ){
int result;
result = x + y;
return result;
}
int main(){
int sum;
sum = integer_add( 5, 12); /* Function Call */
printf("The addition of 5 and 12 is %d\n", sum);
return 0;
}
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 12
The Basics of the C Program
• Summary
– In this lesson you've learned the following:
– A constant in C is a value that never changes. A variable, on the other hand, can
present different values.
– A combination of constants, variables, and operators is called an expression in
the C language. An expression is used to denote different computations.
– The arithmetic operators include +, -, *, /, and %.
– A statement consists of a complete expression suffixed with a semicolon.
– The C compiler treats a statement block as a single statement, although the
statement block may contain more than one statement.
– The function type of a function determines the type of the return value made by
the function.
– You have to follow certain rules to make a valid function name.
– An argument contains information that you want to pass to a function. An
argument list contains two or more arguments that are separated by commas.
– The opening brace ({) and closing brace (}) are used to mark the start and end
of a C function.
– A function body contains variable declarations and statements. Usually, a
function should accomplish just one task.
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 13
2.3 Another Simple C Program:
Adding Two Integers
• 1. Initialize
variables
1
2
3
/* Addition program */
#include <stdio.h>
4
5
int main()
6
{
7
int integer1, integer2, sum;
/* declaration */
printf( "Enter first integer\n" );
/* prompt */
10
scanf( "%d", &integer1 );
/* read an integer */
11
printf( "Enter second integer\n" ); /* prompt */
12
scanf( "%d", &integer2 );
/* read an integer */
13
sum = integer1 + integer2;
/* assignment of sum */
14
printf( "Sum is %d\n", sum );
/* print sum */
8
9
• 2. Input
• 2.1 Sum
• 3. Print
15
16
return 0;
/* indicate that program ended successfully */
17 }
Enter first integer
45
Enter second integer
72
Sum is 117
Spring 2005, Gülcihan Özdemir Dağ
• Program
Output
Lecture 2: page 14
2.3 Another Simple C Program:
Adding Two Integers
• As before
– Comments, #include <stdio.h> and main
• int integer1, integer2, sum;
– Declaration of variables
• Variables: locations in memory where a value can be stored
– int means the variables can hold integers (-1, 3, 0, 47)
– Variable names (identifiers)
• integer1, integer2, sum
• Identifiers: consist of letters, digits (cannot begin with a digit)
and underscores( _ )
– Case sensitive
– Declarations appear before executable statements
• If an executable statement references and undeclared variable
it will produce a syntax (compiler) error
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 15
2.3
Another Simple C Program:
Adding Two Integers
• scanf( "%d", &integer1 );
– Obtains a value from the user
• scanf uses standard input (usually keyboard)
– This scanf statement has two arguments
• %d - indicates data should be a decimal integer
• &integer1 - location in memory to store variable
• & is confusing in beginning – for now, just remember to include it
with the variable name in scanf statements
– When executing the program the user responds to the scanf
statement by typing in a number, then pressing the enter (return)
key
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 16
2.3
Another Simple C Program:
Adding Two Integers
• = (assignment operator)
– Assigns a value to a variable
– Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
– Variable receiving value on left
• printf( "Sum is %d\n", sum );
– Similar to scanf
• %d means decimal integer will be printed
• sum specifies what integer will be printed
– Calculations can be performed inside printf statements
printf( "Sum is %d\n", integer1 + integer2 );
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 17
2.4 Memory Concepts
• Variables
– Variable names correspond to locations in the computer's
memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable (through scanf,
for example), it replaces (and destroys) the previous value
– Reading variables from memory does not change them
• A visual representation
integer1
Spring 2005, Gülcihan Özdemir Dağ
45
Lecture 2: page 18
2.5 Data Types : char
• The char Data Type
– An object of the char data type represents a single character of the
character set used by your computer. For example, A is a character, and so
is a. But 7 is a number.
– But a computer can only store numeric code. Therefore, characters such
as A, a, B, b, and so on all have a unique numeric code that is used by
computers to represent the characters. Usually, a character takes 8 bits
(that is, 1 byte) to store its numeric code.
– For many computers, the ASCII (American Standard Code for
Information Interchange) codes are the de facto standard codes to
represent a character set. The original ASCII character set has only 128
characters because it uses the lower 7 bits that can represent 27 (that is,
128) characters.
– On IBM-compatible PCs, however, the character set is extended to
contain a total of 256 (that is, 28) characters. Appendix C, "ASCII
Character Set," gives a list of the 256 characters.
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 19
2.5 Data Types : char
• Character Constants
– A character enclosed in single quotes (`) is called a character constant. For instance, `A',
`a', `B', and `b' are all character constants that have their unique numeric values in the
ASCII character set. Given x as a character variable, for instance, the following two
assignment statements are equivalent:
x = `A'; x = 65; So are the following two statements:
x = `a'; x = 97;
The Escape Character (\)
In the C language, the backslash (\) is called the escape character; it tells
the computer that a special character follows. For instance, when the
computer sees \ in the newline character \n, it knows that the next
character, n, causes a sequence of a carriage return and a line feed.
Besides the newline character, several other special characters exist in
the C language, such as the following:
Character
Description
\b
The backspace character; moves the cursor to the left one
character.
\f
The form-feed character; goes to the top of a new page.
\r
The return character; returns to the beginning of the current
line.
Lecture 2:
Spring 2005, Gülcihan Özdemir Dağ
\t
The tab character; advances to the next tab stop.
page 20
2.5 Data Types : int
• The int Data Type
•
– You saw the integer data type in Hour 3. The int keyword is used to specify the
type of a variable as an integer. Integer numbers are also called whole numbers,
which have no fractional part or decimal point. Therefore, the result of an
integer division is truncated, simply because any fraction part is ignored.
– Depending on the operating system and the C compiler you're using, the length
of an integer varies. On most UNIX workstations, for example, an integer is 32
bits long, which means that the range of an integer is from 2147483647 (that is,
231_1) to -2147483648. The range of a 16-bit integer is from 32767 (that is,
215_1) to -32768.
Declaring Integer Variables
–
You also saw the declaration of an integer in Hour 3. The following shows the basic declaration
format:
– int variablename; Similar to the character declaration, if you have more than one variable to
declare, you can use either the format like this
int variablename1; int variablename2; int variablename3; or like this:
int variablename1, variablename2, variablename3;
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 21
2.5 Data Types : float
•
The float Data Type
– The floating-point number is another data type in the C language. Unlike an integer
number, a floating-point number contains a decimal point. For instance, 7.01 is a floatingpoint number; so are 5.71 and -3.14. A floating-point number is also called a real number.
– A floating-point number is specified by the float keyword in the C language.
– Like an integer number, a floating-point number has a limited range. The ANSI standard
requires that the range be at least plus or minus 1.0*1037. Normally, a floating-point
number is represented by taking 32 bits. Therefore, a floating-point number in C is of at
least six digits of precision. That is, for a floating-point number, there are at least six
digits (or decimal places) on the right side of the decimal point.
– Not like an integer division from which the result is truncated and the fraction part is
discarded, a floating-point division produces another floating-point number. A floatingpoint division is carried out if both the divisor and the dividend, or one of them, are
floating-point numbers.
• For instance, 571.2 / 10.0 produces another floating-point number, 57.12. So do 571.2 / 10 and
5712 / 10.0.
•
Declaring Floating-Point Variables
– The following shows the declaration format for a floating-point variable:
float variablename;
float variablename1; float variablename2; float variablename3;
or like the following one:
float variablename1, variablename2, variablename3;
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 22
2.5 Data Types: Summary
Data Type
C keyword
İnteger
int
Charachter
char
Floating (real)
float
Double (long float)
double
For engineering notation use
For hexadecimal representation use
For octal representation use
Spring 2005, Gülcihan Özdemir Dağ
Format specifier
%d or %i
%c
%f
%lf
%e or %E
%x or %X
%o or %O
Lecture 2: page 23
2.5 Data Types : Summary contiunes
• / (division operator) has special meaning in such:
4/5 = 0
(int/int)  pay attention to this
4/5.0 = 0.8 (int/float)
4.0/5 = 0.8 (float/int)
4.0/5.0 = 0.8 (float/float)
Type CASTING
(float) 4/5  0.8
(int) 3/6  0
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 24
2.5
Arithmetic
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e., multiplication
before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 25
2.5
Arithmetic
• Arithmetic operators:
C op era tion
Addition
Subtraction
Multiplication
Division
Modulus
Arithm etic
op era tor
+
*
/
%
Alg eb ra ic
exp ression
f+7
p–c
bm
x/y
r mod s
C exp ression
f
p
b
x
r
+
*
/
%
7
c
m
y
s
• Rules of operator precedence:
Operator(s)
()
*, /, or %
+ or -
Operation(s)
Parentheses
Order of evaluation (precedence)
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
Multiplication,Divi Evaluated second. If there are several, they are
sion, Modulus
evaluated left to right.
Addition
Evaluated last. If there are several, they are
Subtraction
evaluated left to right.
Spring 2005, Gülcihan Özdemir Dağ
Lecture 2: page 26
2.6
Keywords in C
• Keywords in C
– Special words reserved for C
– Cannot be used as identifiers or variable names
Keyw ord s
auto
break
case
char
const
continue
default
do
Spring 2005, Gülcihan Özdemir Dağ
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
Lecture 2: page 27