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

Introduction to Scientific and Engineering

Computation (C)
BIL 104E
Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

The person who is looking for Simplicity!


He is the father of
Fourier analysis
He discovered that a
complicated signal can be
represented by sum of simple
signals.
His discover may give us an idea
for this course:
Try to start learning this course
by taking simple steps each day.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Joseph Fourier
2

Brief History of Computing and Computers


2000-2500 BC Abacus is known to be used as a
first tool of computing

1642 Blaise Pascal is first to create a mechanical


adding machine (for tax computations) (was not
reliable)
1670 Gottfried and Leibniz create a reliable adding
machine capable of adding, subtracting, multiplying,
dividing and finding square roots.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

1842 Charles Babbage designs an analytical


engine
to
perform
general
calculations
automatically (accepted as the first design for )

National Museum of Science and Technology (London)


BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

1890 Herman Hollerith designs the first punch card


reader. (Programs are written in punched cards.) Hollerith
starts a company that will eventually become IBM.
1939 John Atasanof (University of Iowa) builds the first
digital computer.
1946 J Presper Eckert and John Mauchly (University of
Pennsylvania) build the Electronic Numerical Integrator and
Calculator (ENIAC). (18000 vacuum tubes costs $500,000)
(Room size: 20m x 50m)

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

A Scientific Calculator (2000s)


The ENIAC Computer (1946)
ENIAC could function much faster than the human brain, its
capability was still lower than a modern scientific calculator
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

1951 Eckert and Mauchly build the first generalpurpose commercial computer called Universal
Automatic Computer (UNIVAC)
1957 FORTRAN is developed as the first high level
language

1958 Transistors are used as switching devices in a


computer (IBM 7090)
1964 The first computer using integrated circuits is
announced (IBM 360)
1975 The first microcomputer is introduced (the
Altair)

1975 The first supercomputer is announced (Cray-1)


BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

1977 Production of first Apple Computers


1981 The first IBM personal computer
1982 Sun Microsystems introduce their first workstation
(Sun 100)
1984 Apple introduces Macintosh, the first widely
available computer with a graphical user interface, using
icons, windows and a mouse device
1992 Personal computers that can handle more than 10
million instructions per second are sold in wide quantities.

1994 Internet (1970) and world wide web (www)


experiences explosive growth and popularity.
2000 Personal computers with microprocessors capable
of handling more than 1 billion instructions are available.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

What is computer?
Computer is a complex digital system.
Capable of performing computations and making
logical decisions
Processing data under the predefined sets of
instructions called computer programs
All computers consist of
hardware, the physical equipment

software , the programs loaded into the hardware


to perform computational tasks.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Computer Organization (1)


Every computer has the following hardware devices:
1.Input devices: keyboard, mouse, scanner
Input information to computer

2.Output devices : screen, printer


Outputs information from computer
3.Memory
Stores input information, rapid access, low capacity.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Computer Organization (2)


4. Arithmetic and logic unit (ALU)
Performs arithmetic calculations and logic
decisions
5. Central processing unit (CPU)
Supervises and coordinates the other sections
of the computer
6. Secondary storage devices (Hard disk, CD-ROM,
DVD-ROM )
Store data and inactive programs
Cheap, long-term, high-capacity storage

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

Computer Organization
Main Memory

Input Devices

Central Processing Unit


(CPU)

Output Devices

Secondary Memory
(File Storage)

A conceptual structure of computer hardware


BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

Computer Organization (3)


Software Components:
1. BIOS (Basic Input Output System)
2. OS (Operating System) such as Unix, DOS, Windows
3. Windowing System such as X-Windows, MS
Windows

4. Applications such as games, word processors,


mathematical programs

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

13

Why do we need to learn any computer


programming language?

To use a computer on the purpose of solving specific


problems in our area of expertise.
To become a good programmer.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

14

Types of programming languages (1)


Three types of programming languages:
1. Machine languages
Strings of numbers giving machine some
specific instructions
Example:
+1300042774
+1400593419
+1200274027

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Types of programming languages (2)


2. Assembly languages
Human language like abbreviations
representing elementary computer operations
(translated via assemblers)
Example:
LOAD
BASEPAY
ADD
OVERPAY
STORE GROSSPAY

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

16

Types of programming languages (3)


3. High-level languages
Much closer to human languages
Mathematical notations can be used
Requires compiler to be translated into machine
language
Example:
grossPay = basePay + overTimePay

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

17

Advantages of High-Level Programming


Languages
Readability: Programs are easy to read.
Maintainability: Programs are easy to maintain.
Portability: Programs are easy to port across
different computer platforms.

C is one of the most popular general-purpose and


high- level programming languages
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

18

History of C ?
The C language was first developed in 1972 by Dennis
Ritchie at AT&T Bell Labs.
He called his program as C, because at that time, B
programming language was already developed !!!

In1978, The book The C Programming Language by


Brian Kernighan and Dennis Ritchie was accepted as
standart for the C.
In 1983, American National Standards Institute (ANSI)
established a committee to provide a standard for C.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

History of C ?
In 1989, the committee approved the ANSI standard
for the C.
In 1999, the ANSI standart was updated.
Today there are many C compilers. However, all of
them support the ANSI standart.
Therefore, all the program text you will learn in this
course can be compiled by any compilers running
under Unix or Windows operating systems.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

20

Why is C?
It does not matter so much. The important point
is to learn the logic of programming. Once
learned, it is very easy to switch to other
programming languages.

Learning C, however, do have several advantages.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

21

Advantages of C?
C is the lowest high level language.
It is the base of many other programming
languages such as C++, Java and operating systems
such as Unix.

Many languages was developed before and after


the C which are faded or not used now. However C
remained by proving its importance.
It offers many great libraries.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

22

Computers brain: CPU (1)


The brain of a computer is the central processing unit
(CPU).

A CPU has millions of transistors employed as electronic


switches. The electronic switches have only two states: off
and on.
0 and 1 are used to represent these two states.
Therefore, a computer can only understand instructions
consisting of series of 0s and 1s.

Instructions to the computer have to be in binary


format.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

23

Computers brain: CPU (2)


However, a computer program written in a high-level
language, such as C consisting of English-like characters
and words
We have to use some special programs, called
compilers or interpreters, to translate such a program
into a machine-readable code.
The code obtained after the translation is called binary
code. Prior to the translation, a program in text format is
called source code.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

24

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.
3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

25

BIL104E
Introduction to Scientific and Engineering
Computation (C)
Instructor: Dr. Fuat Kucuk

WRITING A FIRST PROGRAM IN C LANGUAGE

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Main Parts of a C Program


1. Beginning of the program
2. Declarations (of variables, constants etc)
3. Execution
a) Initialization
b) Reading data from input devices
c) Calculations
d) Writing results to output devices
4. End of the program

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Lets start with a very simple C program (1)


1
2
3
4
5
6

/* Program name: helloworld.c */


#include <stdio.h>
main()
{
printf("Hello World! I'm here to write my first C program. \n");
return 0;
}

The running the compiler, the output is:

Hello World! I'm here to write my first C program


The name of a C program file must have an extension of
.c.
Save filename.c
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Lets start with a very simple C program (2)


1 /* Program name: helloworld.c */

The comments between /* and */ are ignored by the C


compiler. Including comments besides code lines while
writing a program helps you understand what they are for.
You can write comments more than one line either
/* Writing comments in this area does not affect the
size of excecutable file. */
or
/* Writing comments in this area does not affect the */
/* size of excecutable file. */

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Lets start with a very simple C program (3)


2 #include <stdio.h>

#include is a preprocessor directive that tells the program


to load the contents of a particular file.
In this example, #include directive asks to load stdio.h
which is given in <> and called input-output header file.
Header files are required to use predefined functions. For
example printf function is defined in stdio.h.
More header files available in the list of ANSI standart
header files, such as stdlib.h, string.h, math.h, and so on.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Lets start with a very simple C program (4)


3 main()
4 {
5 printf("Hello World! I'm here to write my first C program. \n");
6 }

The execution of the program always starts with the


main () function.
Every program must have only one main () function.

The program ends when all statements within the main ()


function are executed.
The bodies of all functions must be included in braces { }
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Lets start with a very simple C program (5)


5 printf("Hello World! I'm here to write my first C program. \n");

A C library function, printf(), is called in order to print out


what ever inside the quotes .
Note that C is a case sensitive language. Generally all
predefined statements and functions are in lower-case
letters. printf , Printf and PRINTF are not the same.
Line 5 is an entire line called a statement

All statements must end with a semicolon (;)

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Lets start with a very simple C program (6)


5 printf("Hello World! I'm here to write my first C program. \n");

Escape character \ indicates that printf should do


something out of the ordinary.
\n is the newline character. Some common escape
sequences
\n Newline. Position the cursor at the beginning of the next line.
\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\

Backslash. Insert a backslash character in a string.

Double quote. Insert a double quote character in a string.


BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Syntax
When writing a program, a certain set of grammar
rules has to be obeyed.
These rules are called the syntax of the programming
language.
For example, as a syntax rule in C language, a variable
name cannot start with a number.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Compilation Process in C
In order to convert a C program to machine code we
need to compile it. The program that does this job is called
a C compiler.
The compiler takes the C program (source code) and all
the necessary header files required by the program and
produces and object file (.obj).
This object file, if necessary together with other object
files (libraries), is converted to an executable file by
another program called linker. The resulting executable
file can be run on the machine.
In some software development environments such as
MS Visual C++ the compiler and linker can be together.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Errors

There are two kinds of errors:


1. Syntax (Grammar) Errors
2. Semantic (Logical) Errors

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

Syntax Errors
If your program does not obey the grammar
(syntax) rules of the programming language you end
up with syntax errors. For example,
## include <stdio.h>
# include stdio.h
Main()
main
Printf(Hello World);
printf(Hello World)
Compiler usually detects these type of errors.
(compiler errors)
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

Semantic Errors
If there is a problem with the logic of your program
you end up with these kind of errors. These can be
much more difficult to detect and remove.
For example: In a program if we had written z=x-y
instead of z=x+y statement, the program would be
grammatically correct but produce wrong results.
These type of errors are sometimes called run time
errors.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

13

Software Development
Four steps in writing a program:
Specify the problem clearly.
Analyse the problem and break it down into
smaller parts.

Code the program.


Test the program.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

14

Programming practice
1
2
3
4
5
6

/* Program name: helloworld.c */ Newline characters move


the cursor to the next line
#include <stdio.h>
main()
{
printf("Hello World!\n I'm here to write my first C program. \n");
return 0;
}

This program outputs:


Hello World!
I'm here to write my first C program.
return statement is a way to exit function. return 0, in
this case, means that the program terminated normally.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Variables
We use variables to store data.
In C programming language, we need to define the
names and types of variables before starting using them.
For declaring real (floating point) and integer variables,
int and float, respectively.
For example, to declare an integer variable called k we
type
int k;
and to declare three real numbered variables with labels
x,y,z
float x,y,z;
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

16

#include <stdio.h>
main()
{
int i;
i=2+5;
printf("%d \n", i);
}

Defining an integer
variable named i.
Initialization of the
variable.
Prints 7 on the
screen.

This is replaced by
the value of i.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

17

Reserved Words
There are several names called reserved words
(keywords), which may not be used for any purpose
other than they are intended to.
32 reserved words in ANSI C:
auto
break
case
char
const
continue
default
do

double
else
enum
extern
float
for
goto
if

int
long
register
return
short
signed
sizeof
static

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

struct
switch
typedef
union
unsigned
void
volatile
while
18

Identifiers (1)
Other names chosen by the programmer are called
identifiers. The names of variables, functions etc are all
identifiers (they identify an entity in memory).
There are several syntax rules an identifier has to obey:

1. It consists of characters containing the letters (A-Z


and a-z), the digits (0-9) and the underscore
character (_)
2. It cannot start with a digit.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

Identifiers (2)
3. It is case sensitive.
4. If the identifier consists more than 31 characters,
all characters beyond the 31st character may be
ignored by any given compiler.
5. Reserved words cannot be used as identifiers.

An identifier should be defined to indicate the


meaning of its use.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

20

Statements and Statement Blocks


In language C, statement is a complete instruction, ending with
a semicolon (;). For example,
i = 2+3;
return 0;
printf(Hi);
are all statements.

Although not recommended, it is possible to have more than


one statement on a line.
A group of statements can form a statement block that starts
with an openning brace ({) and ends with a closing brace (}).
A statement block is treated as a single statement by the C
compiler. For example, the main() function is formed by a
statement block.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

21

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.

3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

22

BIL104E
Introduction to Scientific and Engineering
Computation (C)
Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Assignments (1)
The assignment statement in C has the following syntax
name = expression;
If necessary, expression is first calculated to determine the
value to be assigned to the variable. For example,

x = y+2;
Do not confuse the equation sign here with mathematical
equations. This assignment could be read in plain English as

Let x be y plus 2 or similarly Assign y plus 2 to x.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Assignments (2)

x = y+2;

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Assignments (3)
In an assignment statement the same variable can
appear in both sides of the statement.
For example,

x = x+1;
is a meaningful assignment and would cause the
value of x to be incremented by 1.
Similarly
x = y * x;
would cause the value of x to be multiplied by the
value of y.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Arithmetic Operators
+
*
/
%

Addition
Subtraction
Multiplication
Division
Remainder

Note that division of integers result


in an integer.
5/3 1
7/8 0
(integer truncation)

Also called as modulus


5%32
14 % 7 0

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Priority of arithmetic operators


Operator(s) Operation(s) Order of evaluation (precedence)
( )

Parentheses

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
Division
Remainder

Evaluated second. If there are several, they are


evaluated left to right.

+
-

Addition
Subtraction

Evaluated last. If there are several, they are


evaluated left to right.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Data input by the user


The library function scanf allows user to input data
from the keyboard.
scanf( "%d", &variable_name);
The function scanf statement has two arguments:
%d indicates data format (int this case, decimal
&variable_name assigns the input word, letter
etc. to the variable_name

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

/* ADDING TWO INTEGER WHICH ARE INPUT FROM KEYBOARD */


#include <stdio.h>
/* function main
int main( void )
{
int integer1;
int integer2;
int sum;

begins program execution */

/* first number to be input by user */


/* second number to be input by user */
/* variable in which sum will be stored */

printf( "Enter first integer\n" ); /* prompt */


scanf( "%d", &integer1 );
/* read an integer */
printf( "Enter second integer\n" ); /* prompt */
scanf( "%d", &integer2 );
/* read an integer */
sum = integer1 + integer2; /* assign total to sum */
printf( "Sum is %d\n", sum ); /* print sum */
return 0;

/* indicate that program ended successfully */

Definitions of
variables
obtains a value from the
user and assigns it to
integer1
obtains a value from the
user and assigns it to
integer2
Assigns a value to
variable sum

Displays the result


of addition

} /* end function main */

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

In the function statements such as printf and scanf,


place a space after each comma (,) to make
programs more readable.
A calculation in an assignment statement must be
on the right side of the = operator. It is a syntax
error to place a calculation on the left side of an
assignment operator.
Do not forget one or both of the double quotes
surrounding the format control string in a printf
or scanf.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Do not forget the % in a conversion specification in


the format control string of a printf or scanf.
Do not place an escape sequence such as \n
outside the format control string of a printf or
scanf.
Do not forget to precede a variable name in a
scanf statement with an ampersand (&) if it is
necessary.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Data Types in C

Fundamental Data Types

Derived Data Types

Integer types

Arrays

Floating Type

Pointers

Character types

Structures
Enumeration

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

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.
A character takes 8 bits (that is, 1 byte) to be stored
in the PCs with its numeric code.

On recent PCs, a total of 256 (that is, 28) characters


are represented by ASCII codes. (ASCII=American
Standard Code for Information Interchange)

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

Declaring Character variables


A variable that can represent different variables is called a
character variable.
Character variables can be declared using the following
syntax:

char variablename1, variablename2, ;


For example,
char ch1,ch2;
defines two character variables ch1 and ch2.
It is then possible, for example
Character constants are enclosed
ch1=A;
in single quotes ()
ch2=65;
Character variables are equivalent.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

13

Giving values to character variables


It is possible to assign character constants such as A, B, C, D to
character variables.
It is also possible to assign the ASCII codes of the characters to
character variables. The C programming language actually treats
character variables as numeric variables: For example, the following
program prints D on the screen.

This is
equivalent to
ch=68;

#include <stdio.h>
main() {
char ch;
ch='A'+3;
printf("%c \n",ch);
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

To print character
variables we use
%c.

14

The int data type


Integer numbers are also called whole numbers, which
have no fractional part or decimal point.
int represents the integer type data.

There is a limitation for representing these numbers.


Depending on the operating system and the C compiler
you're using, the length of an integer varies.
An integer is 32 bits long means the range of an integer
from 2147483647 (that is, 231_1) to -2147483648.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Declaring Integer Variables


General Integer decleration format is
int variablename;
if you have more
int variablename1; int variablename2; int variablename3;
or like this:
int variablename1, variablename2, variablename3;

%d is the format specifier for integers.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

16

The float data type


Unlike an integer number, a floating-point number
contains a decimal point. For instance, 7.01 and -3.14 are
floating-point numbers.
A floating-point number is also called a real number
and represented by float in C.
A floating-point number is represented with 32 bit long,
which takes a range 1.0*1037.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

17

Declaring real numbers


General real number decleration format is
float variablename;
if you have more
float variablename1; float variablename2; float
variablename3;
or like this:
float variablename1, variablename2, variablename3;

%f is number format specifier for real numbers.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

18

/*Integer vs. floating-point divisions , example on format specifiers*/


#include <stdio.h>
main()
{
int int_num1, int_num2, int_num3; /* Declare integer variables */
float flt_num1, flt_num2, flt_num3; /* Declare floating-point variables */
int_num1 = 32 / 10; /* Both divisor and dividend are integers */
flt_num1 = 32 / 10;
int_num2 = 32.0 / 10; /* The divisor is an integer */
flt_num2 = 32.0 / 10;
int_num3 = 32 / 10.0; /* The dividend is an integer */
flt_num3 = 32 / 10.0;

printf("The integer divis. of 32/10 is: %d\n", int_num1);


printf("The floating-point divis. of 32/10 is: %f\n", flt_num1);
printf("The integer divis. of 32.0/10 is: %d\n", int_num2);
printf("The floating-point divis. of 32.0/10 is: %f\n", flt_num2);
printf("The integer divis. of 32/10.0 is: %d\n", int_num3);
printf("The floating-point divis. of 32/10.0 is: %f\n", flt_num3);
return 0;
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

A syntax error will occur if the two symbols in any of the


operators ==, !=, >= and <= are separated by spaces.

= =

! =

> =

< =

A syntax error will occur if the two symbols in any of the


operators !=, >= and <= are reversed. as in
=!

=>

=<

Do not confuse the equality operator == with the


assignment operator =.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

20

Building a function and making a function call


/* Calculate an addition and print out the result */
#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;
}

This is a function called integer add()


that adds two integers

int main()
The function is called and implemented
{
in main () fucntion.
int sum;
sum = integer_add( 5, 12);
printf("The addition of 5 and 12 is %d.\n", sum);
return 0;
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

21

Decision Making
The programs we have been writing so far were
somewhat dull as they were always following the
same sequence of instructions.
One of the main reasons why computers are such
powerful tools is the fact that they can decide
which instructions to follow depending on simple
comparisons.

In C language, the if statement helps us to write


segments of code that will be executed only under
certain conditions.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

22

Declaring if statement

The syntax for the simplest if statement is as follows:


if (expression) {
[Block of Statements]
}
Here expression can be relational expressions, integer values or
variables.
if expression is true (nonzero) then the block of statements in the
if statement are executed otherwise (expression evaluates to zero)
they are skipped.
For example,
if (x < 3) {
printf(x is less than 3! \n);
}
prints the message x is less than 3! on the screen only when x <3.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

23

Equality and Relational Operators


Standard algebraic
equality operator or
relational operator

C equality or
Example of
relational
Meaning of C condition
C condition
operator

Equality operators
=

Relational operators
>
<

==
!=

x == y
x != y

x is equal to y
x is not equal to y

>
<
>=
<=

x>y
x<y
x >= y
x <= y

x is greater than y
x is less than y
x is greater than or equal to y
x is less than or equal to y

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

24

The result of a relational operation is an integer. If


the relation is true then the result is (generally) 1,
otherwise 0.
For example,
3 < 2*5-4
2.1 +3.0 = = 5.0

1, true
0, false

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

25

1
/*
Using if statements, relational
operators, and equality operators */

2
3
4

#include <stdio.h>

5
6

/* function main begins program execution */

int main( void )

8
9

10

int num1; /* first number to be read from user

*/

int num2; /* second number to be read from user */

11
12
13

printf( "Enter two integers, and I will tell you\n" );


printf( "the relationships they satisfy: " );

14
15

scanf( "%d%d", &num1, &num2 ); /* read two integers */

16
17
18
19
20
21
22

if ( num1 == num2 ) {
printf( "%d is equal to %d\n", num1, num2 );
} /* end if */
if ( num1 != num2 ) {

Checks if num1 is equal to num2

Checks if num1 is not equal to num2

printf( "%d is not equal to %d\n", num1, num2 );

23

} /* end if */

24
25
26
27

if ( num1 < num2 ) {


printf( "%d is less than %d\n", num1, num2 );
} /* end if */

Checks if num1 is less than num2

28

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

26

(continued on next slide )


Checks if num1 is greater than num2

29

if ( num1 > num2 ) {

30
31

printf( "%d is greater than %d\n", num1, num2 );


} /* end if */

32
33
34
35
36
37

Checks if num1 is less than or equal to num2

if ( num1 <= num2 ) {


printf( "%d is less than or equal to %d\n", num1, num2 );
} /* end if */
if ( num1 >= num2 ) {

Checks if num1 is greater than equal to num2

38
printf( "%d is greater than or equal to %d\n", num1, num2 );
39
} /* end if */
40
41
return 0;
/* indicate that program ended successfully */
42
43 } /* end function main */
43 } /* end function main */
Enter two integers, and I will tell you
the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

27

CAUTIONS
Do not a semicolon immediately to the right of the
right parenthesis after the condition in an if
statement.
Place a blank line before and after every if
statement in a program for readability.
Although it is allowed, there should be no
more than one statement per line in a program.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

28

Logical Operations
It is possible to connect logical expressions using logical
operations, which usually take the following syntax:
L1 <logic_operator> L2
Here L1 and L2 are logic expressions and the logic operator
can be && (and), or || (or).
The result of a && (and) operation is 1 (true) only if both
logical expressions (L1 and L2) are nonzero (true).
The result of a || (or) operation is 1 (true) if one of the
logical expressions (L1 or L2) is nozero (true).

Truth tables for && and || operations:


0 && 0 0
0 || 0 0
0 && 1 0
0 || 1 1
1 && 0 0
1 || 0 1
1 && 1 1
1 || 1 1
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

29

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.

3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

30

Introduction to Scientific and Engineering


Computation (C)
BIL 104E
Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Decision Making
The programs we have been writing so far were
somewhat dull as they were always following the
same sequence of instructions.
One of the main reasons why computers are such
powerful tools is the fact that they can decide
which instructions to follow depending on simple
comparisons.
In C language, the if statement helps us to write
segments of code that will be executed only under
certain conditions.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Declaring if statement
The syntax for the simplest if statement is as follows:
if (expression) {
[Block of Statements]
}
Here expression can be relational expressions, integer values or
variables.
if expression is true (nonzero) then the block of statements in the
if statement are executed otherwise (expression evaluates to zero)
they are skipped.
For example,
if (x < 3) {
printf(x is less than 3! \n);
}
prints the message x is less than 3! on the screen only when x <3.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

1
2
3
4

/*
Using if statements, relational
operators, and equality operators */
#include <stdio.h>

5
7

/* function main begins program execution */


int main( void )

9
10

int num1; /* first number to be read from user */


int num2; /* second number to be read from user */

11
13

printf( "Enter two integers, and I will tell you\


you\n" );
printf( "the relationships they satisfy: " );

14
15

scanf( "%d%d",
"%d%d", &num1, &num2 ); /* read two integers */

12

16
17
18
19
20
21
22
23

if ( num1 == num2 ) {
printf( "%d is equal to %d\
%d\n",
n", num1, num2 );
} /* end if */

Checks if num1 is not equal to num2

if ( num1 != num2 ) {
printf( "%d is not equal to %d\
%d\n",
n", num1, num2 );
} /* end if */

24
25
26
27

Checks if num1 is equal to num2

if ( num1 < num2 ) {


printf( "%d is less than %d\
%d\n",
n", num1, num2 );
} /* end if */

Checks if num1 is less than num2

28

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

(continued on next slide )


29
30
31
32
33
34
35
36
37
38
39
40
41

if ( num1 > num2 ) {


printf( "%d is greater than %d\
%d\n",
n", num1, num2 );
} /* end if */

Checks if num1 is greater than num2

if ( num1 <= num2 ) {


printf( "%d is less than or equal to %d\
%d\n",
n", num1, num2 );
} /* end if */

Checks if num1 is less than or equal to num2

if ( num1 >= num2 ) {


printf( "%d is greater than or equal to %d\
%d\n",
n", num1, num2 );
} /* end if */

Checks if num1 is greater than equal to num2

return 0;

/* indicate that program ended successfully */

42
43 } /* end function main */
43 } /* end function main */

Enter two integers, and I will tell you the relationships they satisfy:
37
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

 Do not put a semicolon immediately to the right of


the right parenthesis after the condition in an if
statement.
 Place a blank line before and after every if
statement in a program for readability.
 Although it is allowed, there should be no
more than one statement per line in a program.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

If statement (example)
Write a program that asks the age of the user and if the
user is between 13 and 19 it prints out You are a teenager.
#include <stdio.h>
main()
{
int age;
printf("Your age: ");
scanf("%d",&age);
printf("Age : %d\n", age);
if((age>=13) && (age<=19)) {
printf("You are a teenager!\n");
}
}

Your age: 15
Age : 15
You are a teenager!
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

if - else statement
Sometimes we expect our program to do another task if a
defined condition is not satisfied.
The else statement can be used for this purpose. The syntax of
the if else statement is as follows:
if (expression) {
[First block of C statements]
}
else {
[Second block of C statements]
}
Here, if the expression is not true (zero), the second block of C
statements will be executed.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

The following program prints out You are a teenager!, if the user
is between 13 and 19, otherwise it prints out You are NOT a
teenager!.
#include <stdio.h>
main()
{
int age;
printf("Your age: ");
scanf("%d",&age);
printf("Age : %d\n", age);
if((age>=13) && (age<=19))
printf("You are a teenager!\n");
else
printf("You are NOT a teenager!\n");
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Note that
since there
are only one
statements in
statement
blocks we did
not have to
use the
braces, {}.

Nesting if Statements (1)


It is possible to use if statements inside other if statements.
For example,
#include <stdio.h>
main()
{
int age;
Nested if
printf("Your age: ");
statement
scanf("%d",&age);
printf("Age : %d\n", age);
if(age<13)
printf("You are a kid!\n");
else
if((age>=13) && (age<=19))
printf("You are a teenager!\n");
else
printf("You are NOT a teenager!\n");
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Nesting if Statements (2)

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

Nesting if Statements (3)


You are a kid, if the user is younger than 13
You are a teenager, if the user is between 13 and 19
You are young, if the user is between 20 and 34
You are not young, if the user is older than 34
#include <stdio.h>
main()
{
int age;
printf("Your age: ");
scanf("%d",&age);
if(age<13)
printf("You are a kid!\n");
else if(age<20)
printf("You are a teenager!\n");
else if(age<35)
printf("You are young!\n");
else printf("You are not young!\n");
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

Increment and Decrement Operators (1)


 Increment operator (++)
 Decrement operator (--)
 Preincrement
Operator is used before a variable (++c or --c)
Variable is changed before the expression is
evaluated
 Postincrement
Operator is used after the variable (c++ or c--)
Expression executes before the variable is changed
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

13

Increment and Decrement Operators (2)


 If c equals 5, then
printf( "%d", ++c );/*prints 6*/
printf( "%d", c++ );/*prints 5*/
 In either case, c now has the value of 6
 When variable not in an expression preincrementing and
postincrementing have the same effect:
++c;
printf( %d, c );
and
c++;
printf( %d, c );
have the same output
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

14

Increment and Decrement Operators


Operator

Sample
Explanation
expression

++

++a

Increment a by 1, then use the


new value of a in the expression
in which a resides.

++

a++

Use the current value of a in the


expression in which a resides,
then increment a by 1.

--

--b
--b

Decrement b by 1, then use the


new value of b in the expression
in which b resides.

--

b--

Use the current value of b in the


expression in which b resides,
then decrement b by 1.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Loops
One strong side of computers is that they can do
repetitive jobs very quickly, and without getting
bored.
Doing repetitive blocks of code are called loops in
computer terminology.
In C, loops are implemented by means of while,
do .. while, or for statements.

16
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

16

The while Loop (1)


The purpose of the while loop is to execute a statement
again and again while a given condition is true.
 The syntax is as follows:
while (expression) {
statements
}

 When a C code reaches to a while statement


1. The expression is evaluated.
2. If the expression false (zero), the while statement
terminates.
3. If condition results true (nonzero), the C
statement(s) are executed.
4. Execution returns to step 1.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

17

The while Loop (1)


 For example,
i=1;
while (i<5) {
printf(2 x %d = %2d\n, i, 2*i);
i++;
}

2
2
2
2

x
x
x
x

1
2
3
4

=
=
=
=

2
4
6
8

Note that in a while loop, first the expression in while


statement (the termination condition) is calculated. If the
expression is zero than the statement(s) in the loop are
not executed.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

18

For Loop
 Many loops require a certain task to be repeated for a number
of times. There is a special statement called for statement for
this purpose. The syntax is as follows:
for (expression1; expression2; expression3)
statement;

 In the For loop,


expression1 is an initialization of (giving first value to) a
variable (usually referred as the counter or loop
variable).
expression2 is usually a conditional expression, is
evaluated. If the expression evaluates to a nonzero
value, the for loop is repetitively executed.
Expression 3 is usually an increment or decrement
statement.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

While loop vs For loop


for (expression1; expression2; expression3)
statement;

expression1;
while(expression2) {
statement;
expression3;
}

i=1;
while (i<5) {
printf(2 x %d = %2d\n, i, 2*i);
i++;
}

Same results

for(i=1;i<5;i++)
printf(2 x %d = %2d\n, i, 2*i);
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

20

Analysis of a Loop (1)


#include <stdio.h>
main()
{
int count;
for(count=0;count<5;count+=2)
printf(count=%d \n", count);
printf("After for loop: count=%d \n", count);
}

count=0
count=2
count=4
After for loop: count=6
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

21

int count;

count
?

Analysis

for (count=0; count<5; count+=2)


{
count
count=0
0
Is (count < 5)  true  continue
printf ...
count
count+=2
2

1st loop

Is (count < 5)  true  continue


printf ...
count+=2

count
4

2nd loop

Is (count < 5)  true  continue


printf ...
count+=2

count
6

3rd loop

Is (count < 5)  false  exit the for


loop
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

22

Remarks
 Though not recommended, C allows direct assignments to for
variable (counter) inside the loop. For example,
for (i = 1;i<17;i+=2) {
printf (%d\n, i);
if (i>5)
i = i + 2; /* This is possible */
}

1
3
5
7
11
15

 Note that there is no semicolon after the for statement. If you


accidentally put a semicolon it wont produce a syntax error
since semicolon is a null (do nothing) statement in C.
However, your program will not work as you wish it to work.
for (i = 1;i<17;i++);

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

This means count from 1 to


17 do nothing else.
23

Examples for counter values


for statement

counter values

for (i=1;i<=3;i++)

1,2,3

for (j=1;j<12;j+=3)

1,4,7,10

for (k=78;k>40;k-=10)

78,68,58,48

for (p=-15;p<=15;p+=5)

-15,-10,-5,0,5,10,15

for (r=12;r>10;r-=3)

12

for (i=1;i>5,i++)

(for loop is skipped)

for (i=7;i<3;i--)

(for loop is skipped)

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

24

Analysis Before Writing a C code


Write a program that asks the number of students in a class,
asks the mark of each student and calculates the average mark.
ANALYSIS:
1. First the number of students has to be read from the
keyboard. (num_of_studs)
2. Then, in a for loop with initial value 1 and final value
num_of_studs the mark of each student (mark) should be
read and the sum of marks, which is kept in a separate
variable (mark_sum), should be updated. In order for this
idea to work, mark_sum has to be initialised to 0.0 before
the for loop.
3. Finally, the average is found as mark_sum / num_studs and
printed out.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

25

#include <stdio.h>
main()
{
int i, num_of_studs;
float mark, mark_sum=0.0;
/* Get the number of students */
printf("How many students in the class?\n");
scanf("%d",&num_of_studs);
/* Read the mark of each student and update mark_sum */
for(i = 1;i<=num_of_studs;i++) {
printf("What is the mark of Student %d?\n",i);
scanf("%f",&mark);
mark_sum = mark_sum + mark;
}
/* Print out the result */
printf("Average of marks : %4.1f\n", mark_sum/num_of_studs);

}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

26

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.
3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

27

Introduction to Scientific and Engineering


Computation (C)
BIL 104E
Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Example: factorial calculation

Write down a C code that finds the factorial of a any


given number.
Factorial of n= n!=n*(n-1)*(n-2)*...*1

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Example: factorial calculation


#include <stdio.h>
main()
{
long int i, n, fact=1;
printf("Enter the number n=");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
fact *= i; /* fact =fact* i; */
}
printf(n! = %ld \n",fact);
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

We have used long int to ensure


that large integer numbers can
be represented.
ld format specifier is used to
format the number as a long
decimal number.
Enter the number n=10
n! = 3628800

The do .. while Loop


Sometimes the statement(s) inside the loop is required to be
executed at least once before checking for the termination
condition. In such cases, the do .. while loop can be used.
It is most appropriate when the statement(s) associated with the
loop must be executed at least once.
The syntax is as follows:
do
statement;
while ( condition);

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

The statement is executed first and


then executed repetitively while
the expression is nonzero.

Example: do-while loop


1 /*
2 Using the do/while repetition statement */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int counter = 1; /* initialize counter */
9
10
do {
11
printf( "%d ", counter ); /* display counter */
12
} while ( ++counter <= 10 ); /* end do...while */
13
14
return 0; /* indicate program ended successfully */
15
16
} /* end function main */

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Assignment Operators
Assignment operators abbreviate assignment expressions
c = c + 3;
can be abbreviated as c += 3; using the addition assignment operator.
Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
Examples of other assignment operators:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Priority of the operators encountered so far


Operators

Associativity

++ (postfix)

-- (postfix)

Type

right to left

postfix

right to left

unary

* / %

left to right

multiplicative

left to right

additive

left to right

relational

left to right

equality

right to left

conditional

right to left

assignment

+ -

( type)

< <=
==

++ (prefix) -- (prefix)

>

>=

!=

?:
=

+=

-=

*=

/=

%=

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

If statement with a loop


Note that you can use if statements in loops, loops in if
statements, and nest these in any order you want if necessary.
The following program finds the sum of positive odd numbers
between 1 and n where n is a number entered by the user.
#include <stdio.h>
main()
{
int i,n,sum=0;
printf(n=?\n);
scanf(%d,&n);
if (n>0)
for(i=1;i<=n;i++)
if((i%2) == 1)
sum+=i;
printf(sum = %d\n,sum);
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Note that we could have


used i+=2 here and not use
the if statement inside the
loop.
n=?
10
sum = 25
8

Nested Loops
A loop inside another one is called nested loops.
With this structure, the progress of inner loop is
dependent on the progress of outer loop.
Suppose you have two nested loops. If the
statements are satisfied, the program will first execute
the outer loop once and run the inner loop completely
before starting the second execution of the outer loop.
These looping contiues until the outer loop excecution
finishes.
C places no limitations on the nesting of loops, except
that each inner loop must be enclosed completely in
the outer loop
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Example: nested loops


/* Demonstrating nested loops */
#include <stdio.h>
main()
{
int i, j;
for (i=1; i<=3; i++) { /* outer loop */
printf("The start of iteration %d of the outer loop.\n", i);
for (j=1; j<=4; j++) /* inner loop */
printf(" Iteration %d of the inner loop.\n", j);
printf("The end of iteration %d of the outer loop.\n", i);
}
return 0;
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Output of the program:

The start of iteration 1 of the outer loop.


Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 1 of the outer loop.
The start of iteration 2 of the outer loop.
Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 2 of the outer loop.
The start of iteration 3 of the outer loop.
Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 3 of the outer loop.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

Avoid from overlapping !


for ( count = 1; count < 100;
count++)
{
do
{
/* the do...while loop */
} /* end of for loop */
overlapping
}while (x != 0);
for (count = 1; count < 100; count++)
{
do
{
/* the do...while loop */
}while (x != 0);
} /* end of for loop */
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

Turn back to factorial program...


#include <stdio.h>
main()
{
long int i, n, fact;
printf("Enter the number n=");
scanf("%d",&n);
while (n!=-1){
fact=1;
for(i=1; i<=n; i++)
{
fact =fact* i; * / fact *= i; also OK */
}
printf("n! = %d \n",fact);
printf("Enter the number n=");
scanf("%d",&n);
}
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Using nested loops allows


us to continue factorial
calculation forever unless -1
entered.

13

Multiple expressions in a for statement


It is possible to give more than one statements in expression1
and expression3 parts of a for statement. In such a case, the
expressions should be separated by commas. For example,

for (i=0, j=10; i!=j; i++, j--)


printf((%d,%d)\n, i, j);
prints out (0,10), (1,9), (2,8), (3,7), (4,6) on the screen in
separate lines.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

14

Breaking Loops
Sometimes it is required to exit a loop. This usually
happens when an error is detected, or a certain
condition related to the nature of the loop is
encountered.
break statement can be used for this purpose.
When a break statement is encountered in a loop,
the execution continues from the first line that is out of
the loop.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Example: break statement


int x;
printf ( "Counting from 1 to 10\n" );
/* having no condition in a for loop causes looping forever */
for( x = 1; ; x++ )
{
if( x == 10 ) /* This checks for the value of 10 */
break; /* This ends the loop */
printf( "\n%d", x );
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

16

Jumping to the End of Loops


Sometimes it is required to jump to the end of a loop
without exiting the loop.
It is possible to use the continue statement for such
purposes.
In execution time, when a continue statement is
encountered the execution continues from the brace
that closes the loop.
This means expresion3 in a for loop will be executed
and the loop will continue to do its work.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

17

Example: continue statement


int x;
printf("Printing only the even numbers from 1 to 10\n");
for( x = 1; x <= 10; x++ )
{
if( x % 2 != 0 ) /* See if the number is NOT even */
continue; /* Get next instance x */
printf( "\n%d", x );
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

18

Infinite Loops
Sometimes it is required to exit a loop when a certain condition is
met and unless this condition is met the loop is required to continue
infinitely. Such loops are called infinite loops. In C language, it is
possible to use loops with the following syntax in order to
implement infinite loops:
for (;;) {
[Block of C Statements]
}

while {
[Block of C Statements]
}

To avoid an infinite loop, there has to be a break statement in the


loop (most probably inside an if statement).

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

Example

Write a program that asks the marks of students in a class


and calculates the average mark. The process of entering
the marks should be terminated when 1.0 is entered as a
mark of a student. Furthermore, the program should make
sure that all the marks entered are valid marks (i.e. they are
between 0 and 100).

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

20

#include <stdio.h>
Infinite
main() {
int num_of_studs=0;
loop!
float mark_sum=0.0, mark;
/* Read the mark of each student and update mark_sum */
for(;;) {
printf("What is the mark of Student %d?\n",num_of_studs+1);
scanf("%f",&mark);
if (mark == -1.0)
This means continue
break;
else if((mark <0.0) || (mark >100.0)) from here!
{
printf("Invalid mark!\n");
This means continue
continue;
}
from here!
num_of_studs++;
mark_sum += mark;
}
/* Print out the result */
printf("Number of students :%d\n", num_of_studs);
printf("Average of marks : %4.1f\n", mark_sum /
num_of_studs);
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

21

A sample output of the program

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

22

The goto statement


In order to continue execution from a certain point in
the program the goto statement can be used. The
syntax is:
labelname:
statement1;
statement2;
...
goto labelname;
This kind of programming is very poor and is not
recommended. So avoid using goto statements in your
programs.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

23

Example: goto statement (1)


1: /* Demonstrates the goto statement */
2:
3: #include <stdio.h>
4:
5: main()
6: {
7: int n;
8:
9: start: ;
10:
11: puts("Enter a number between 0 and 10: ");
12: scanf("%d", &n);
13:
14: if (n < 0 ||n > 10 )
15:
goto start;
16: else if (n == 0)
17:
goto location0;
Continued
18: else if (n == 1)
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

24

Example: goto statement (2)


19:
goto location1;
20: else
21:
goto location2;
22:
23: location0: ;
24: puts("You entered 0.\n");
25: goto end;
26:
27: location1: ;
28: puts("You entered 1.\n");
29: goto end;
30:
31: location2: ;
32: puts("You entered a number between 2 and 10.\n");
33:
34: end: ;
35: return 0;
36: }
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

25

switch Statement
The logical expressions in nested if statements can become very
messy when there are many decisions to make. The switch statement
can be used to make decisions where to jump in the program
depending on the value of an expression. The syntax is as follows:
switch (expression) {
case case_expression_1:
[First Block of C Statements]
case case_expression_2:
[Second Block of C Statements]
default:
[Default Block of C Statements]
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

26

#include <stdio.h>
main()
{
int category;
printf("Enter category (1-3): ");
scanf("%d",&category);
switch(category) {
case 1:
printf("Category 1\n");
break;
case 2:
printf("Category 2\n");
break;
case 3:
printf("Category 3\n");
break;
default:
printf("Wrong category
number!\n");
}
}

Enter category (1-3): 5


Wrong category number!

Enter category (1-3): 2


Category 2

Without break statements


the output would be:
Category 2
Category 3
Wrong category number!

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

27

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez

2) SAMS Teach Yourself C" by T Zhang.


3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

28

Introduction to Scientific and Engineering


Computation (C)
BIL 104E
Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Formatting Output (1)


It is possible to determine the minimum field width in
a format specifier by using an integer just after the
percent sign. For example,
printf(%d\n,12);
printf(%4d\n,12);

Prints 12 on the screen.


Prints 2 spaces and 12
on the screen.

12
12

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Formatting Output (2)


A positive integer between the % and format specifier
(d, f etc.) right-justifies the output whereas a negative
integer can be used for left-justifying.
Right-justifying

printf(%5d%-5d\n,1,1);
printf(%5d%-5d\n,12,12);
printf(%5d%-5d\n,123,123);
printf(%5d%-5d\n,1234,1234);

11
1212
123123
12341234

Left-justifying
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Adjusting the precision (1)


It is possible to determine the precision of the floating
point numbers to be shown on the screen. This is done
by using %n1.n2f format specifier.
Here n1 is an integer that determines the length of
the output and n2 is the number of decimal digits to be
used after the dot(.).
n2 defines the size of the fractional part for real
numbers, whereas it means the minimum field length
for integers.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Adjusting the precision (2)


printf("%6.3f\n",1.2);
printf("%6.3f\n",12.34);
printf("%6.3f\n",12.3456);
printf("%6.3f\n",123.456);
printf("%6.3f\n",123.4567);
printf("%6.3d\n",11);

1.200
12.340
12.346
123.456
123.457
011

Zero
addition
Rounding
up!

Note that when an integer is formatted with a precision specifier


the second number means the minimum field length.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

More about data types (1)


Depending on the required precision and range the
programmer might want to use one of the following modifiers:
The short modifier states that the programmer requires the
data type to occupy less space in memory (which results in less
accuracy or smaller range of values that can be represented by
the type). For example,

short int i, j, k;
The long modifier states that the programmer requires the
data type to occupy more space in memory (which results in
higher accuracy or larger range of values that can be represented
by the type). For example,
long int bigvalue;

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

More about data types (2)


long and short modifiers are not allowed to be used with float. To
have more accurate floating point numbers we use the type double.
For example,
double x;
defines a high accuracy floating point number with name x.

Using long double it might be possible to obtain even higher


accuracies. The number of bytes used for representing variables in
different types depends on the machine.
The number of bytes used for a specific type or for a given variable
can be learned by using the sizeof() function. For example,
long int k;
printf(Memory size for k: %d\n,sizeof(k));
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

More about data types (3)


When working with derivations of integer type, it is possible to
state whether the variables represent only positive values or both
positive and negative values, by using unsigned and signed
modifiers respectively.
For example for a system where 16 bits are used for integers,
char ch; /* x can hold values between 128 (27) and 127 (27 1) */
unsigned char uch; /* uch can hold values between 0 and 255 (28 1) */
int x; /* x can hold values between -32768 (215) and 32767 (215 1) */
signed int y; /* the same as int y */
unsigned int z; /* z can hold values between 0 and 65535 (216 1) */
long int lx; /* lx can hold values between (231) and (231 1) */
signed long int ly; /* the same as long int ly */
unsigned long int lz; /* lz can hold values between 0 and (232 1) */
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Mathematical Functions (1)


There are many mathematical functions available in C
libraries.
We can use C library functions directly instead of writing a
code for the same purpose.

In order to use math functions, math header file must be


called.
We frequently use the following functions in mathematics.
Trigonometric functions: sin(x), cos(x),
Exponential functions ex, 10x
Logarithmic functions: lnx, log10x
Polynomial functions: f ( x ) x 3 2 x 2 5 x 4

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Mathematical Functions (2)


Syntax of calling math library
#include <math.h>

Syntax of making a mathematical calculation


function_name( argument );

Argument can be variable, expression or a constant


All math functions return data type double
If there are multiple arguments, use comma to seperate them.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Mathematical Functions (3)


Some of the mathematical functions defined in math library.
sqrt(x) Square Root
pow(x,y) power (y power of x)
sin(x), cos(x), tan(x) Trigonometric functions
asin(x), acos(x), atan(x) Trigonometric functions
exp(x), log(x), log10(x) Exponential, natural log, log in base 10
ceil(x), round(x), floor(x) Converting to integer
Examples of using math functions
t=2*sin(0.5)/log(x+4.0) ;
y=asin(cos(2*x));
printf( "%.2f", sqrt( 900.0 ) );
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

Example

math.h library is
used so that we can
make use of sin()
function.

#include <stdio.h>
#include <math.h>
main()
{
double x;
const double PI = 3.14159265358979323846;
for(x=0.0; x<=90.0; x+=15.0)
printf("Sin(%2.0lf) = %5.3lf\n",x ,sin(x *
PI/180.0));
}
Sin( 0)
Sin(15)
Sin(30)
Sin(45)
Sin(60)
Sin(75)
Sin(90)

=
=
=
=
=
=
=

0.000
0.259
0.500
0.707
0.866
0.966
1.000

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Trigonometric
functions use radians.
So we have to convert
to radians first.

12

Example

Write down a program that asks for an angle and finds the sinus of
that angle approximately. Use the following equation

(1) k 1 x 2k 1
Sin( x)
(2k 1)!
k 1
n

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

13

Analysis:
First the angle should be read and assigned a variable (angle).
Then the angle should be converted to radians (x).

The sinus of the angle should be kept in a variable (sin_x).


The sinus can be updated in a for loop. In each loop the kth term of
the sum should be calculated and added to sin_x.
In order to calculate the kth term 3 temporary variables can be
used (sign, x_to_2k1, fact). At the beginning of each loop these
should give (-1)k+1, x2k+1, and (2k1)! respectively. At the end of each
loop the temporary variables should be updated for the next loop.
The variables sin_x, sign, x_to_2k1 and sin_x should have proper
values before starting the for loop.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

14

const is used to define


constants (These
cannot be change in
execution time).

#include <stdio.h>
#include <math.h>
main()
{
double is used for
const int n=5;
high precision
const double pi=3.14159;
long int k, fact=1;
(instead of float).
double angle, x, x_to_2k1, sign=1, sin_x=0.0;
printf("Enter an angle in degrees:");
scanf("%lf",&angle);
x_to_2k1=x=angle*pi/180.0; /* First convert to radians */
for(k=1; k<=n; k++)
{
k 1
(

1
)
x_to_2k1 =pow(x,2*k-1);
x2k 1 (2k 1)!
if (k>1)
fact *=(2*k-2)*(2*k-1);
sin_x = sin_x + sign * x_to_2k1 / fact;
lf format specifier is used to
sign= -sign;
format the number as a
}
printf("Sinus %lf is %4.2lf. \n",angle,sin_x);
double precision number.
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

When you call a math.h function


When you use a function in an expression, the function argument is
evaluated at first.
The value of argument then transferred to the function.
Function values for this argument is evaluated and the function is
replaced with its value.
Finally the expression that contains the function is evaluated.
For example,
x=30.0;
y = 1.5 + sin(x * PI/180.0);
First, x*PI/180.0 (0.523...) is evaluated. Then, sin() function is
called. The function call statement (ie sin(x * PI/180.0)) is replaced by the
result of the function (0.5). Last, the statement y=1.5+0.5; is evaluated.
Hence, at the end of the second statement the variable y is 2.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

16

Random Number Generation


To generate random numbers, first, stdlib header file must be loaded.
#include <stdlib.h>

Rand function generates numbers between o and RAND_MAX (at


least 32767).
Example of using the function
i = rand();

To get a random number between 1 and n (scaling)


1 + ( rand() % n );

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

17

Example: random number generation


1 /* Fig. 5.7: fig05_07.c
Shifted, scaled integers produced by 1 + rand() % 6 */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 /* function main begins program execution */
7 int main( void )
8 {
int i; /* counter */
9
10
/* loop 20 times */
11
for ( i = 1; i <= 20; i++ ) {
12
13
/* pick random number from 1 to 6 and output it */
14
printf( "%10d", 1 + ( rand() % 6 ) );
15
16

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

18


17
/* if counter is divisible by 5, begin with new line
*/
18
if ( i % 5 == 0 ) {
19
printf( "\n" );
20
} /* end if */
21
22
} /* end for */
23
24
return 0; /* indicates successful termination */
25
26 } /* end main */

The output:

6
5
6
6

6
1
6
2

5
1
2
3

5
5
4
4

6
3
2
1

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

Defining your own functions


Defining and calling a function is often required in a C
programming.
The syntax for defining a function is as follows:
Type_of_result function_name(type1 arg1, type2 arg2, ...)
{
[Block of C statements]
}
Here, arg1, arg2, ... are called as the arguments of the function.
The parameters of a function are sent via the arguments. We shall
see that arguments can also be used to provide additional outputs
to the function.

A function declaration is the interface part (the part without the


main body) of the function. Functions must be declared before
they are used.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

20

Example: your own function


#include <stdio.h>
/* Definition of the Times2() function */
double Times2(double x)
{
Note that you cannot make
double y;
changes on (make assignments to)
y=2*x;
arguments. For example,
return y;
x = 2*x;
}
is not allowed here.
/* Main function */
/* This is where the program starts execution */
main()
{
/* Call Times2 function */
printf("2 times 5 is %4.0lf\n", Times2(5));
}

2 times 5 is
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10
21

#include <stdio.h>
/* Defining Factorial and Sinus functions */
double Factorial(double n)
Note that the variable i here is different from the
{
variable i in Sinus function. Variables defined in
double i,fact=1.0;
functions are called local variables. They can be
for(i=2.0;i<=n;i++)
{
used only inside the function. When function
fact *= i;
terminates all local variables are removed from
}
memory.
return fact;
}
The same rule applies for the arguments. Hence
double Sinus(double x)
the variable x here is different (as a memory
{
location) from the variable x in main() function.
const int n=5;
int i;
double x_to_2k1=x, sign=1.0, sin_x=0.0;
for(i=1;i<=n;i++)
{
sin_x += sign * x_to_2k1 / Factorial((double) 2*i-1);
sign=-sign;
This is called casting. The
x_to_2k1*= x*x;
expression on the right is
}
return sin_x;
converted to a double. For this
}
particular example has no effect
/*Program continues on the next page*/!
on the program.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

22

main()
{
double x;
const double PI = 3.14159265358979323846;
for(x=0.0; x<=90.0; x+=15.0)
printf("Sin(%2.0lf) = %5.3lf\n",x,Sinus(x*PI/180.0));
}

Sin( 0)
Sin(15)
Sin(30)
Sin(45)
Sin(60)
Sin(75)
Sin(90)

=
=
=
=
=
=
=

0.000
0.259
0.500
0.707
0.866
0.966
1.000

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

23

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.

3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

24

Introduction to Scientific and Engineering


Computation (C)
BIL 104E

Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

POINTERS
What Is a Pointer?
A pointer is a variable whose value is used to point to
another variable.
From this definition, you know two things:
first, that a pointer is a variable, so you can assign
different values to a pointer variable,

second, the value contained by a pointer must be an


address that indicates the location of another variable
in the memory.
That's why a pointer is also called an address variable.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Address (Left Value) Versus Content (Right Value)


The memory inside your computer is used to hold the
binary code of your program.
Each memory location has a unique address so that the
computer can read from or write to the memory location
without any confusion.
This is similar to the concept that each house in a city
must have a unique address.
When a variable is declared, a piece of unused memory
will be reserved for the variable, and the unique address to
the memory will be associated with the name of the
variable.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Address (Left Value) Versus Content (Right Value)


The address associated with the variable name is usually
called the left value of the variable.
When the variable is assigned a value, the value is stored
into the reserved memory location as the content. The
content is also called the right value of the variable.
Sometimes it is required to pass large amounts of data
between functions, or allocate memory locations
dynamically. Instead of using variables, more flexible way is
to use pointers.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Address-of Operator (&)


It is possible to find the actual address of a variable using the &
operator. For example,
This finds the
#include <stdio.h>
main() {
int k=5;
float x=3.14;
printf("Value of k
printf("Address of
printf("Value of x
printf("Address of
}

Value of k
Address of
Value of x
Address of

address of the
variable k.
is %d\n",k);
k is %p\n",&k);
is %f\n",x);
x is %p\n",&x);
Note that we use %p
to format the
memory address.

is 5
k is 0065FDF4
is 3.140000
x is 0065FDF0

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

The presentation of the


address format can change
from compiler to compiler.
5

Declaring and Assigning Values to Pointers


The general form of a pointer declaration is

data-type *pointer-name;
Here data-type specifies the type of data to which the
pointer points. Pointer-name is the name of the pointer
variable, which can be any valid variable name in C.
There is an an asterisk (*) just before the pointer name,
which indicates that the variable is a pointer.
When the compiler sees the asterisk in the declaration, it
makes a note in its symbol table so that the variable can be
used as a pointer.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

1: /* Declaring and assigning values to pointers */


2: #include <stdio.h>
3:
4: main()
5: {
6: char c, *ptr_c;
7: int x, *ptr_x;
8: float y, *ptr_y;
9:
10: c = 'A';
11: x = 7;
12: y = 123.45;
13: printf("c: address=0x%p, content=%c\n", &c, c);
14: printf("x: address=0x%p, content=%d\n", &x, x);
15: printf("y: address=0x%p, content=%5.2f\n", &y, y);
16: ptr_c = &c;
17:
printf("ptr_c: address=0x%p, content=0x%p\n", &ptr_c, ptr_c);
18:
printf("*ptr_c => %c\n", *ptr_c);
19: ptr_x = &x;
20:
printf("ptr_x: address=0x%p, content=0x%p\n", &ptr_x, ptr_x);
21:
printf("*ptr_x => %d\n", *ptr_x);
22: ptr_y = &y;
23:
printf("ptr_y: address=0x%p, content=0x%p\n", &ptr_y, ptr_y);
24:
printf("*ptr_y => %5.2f\n", *ptr_y);
25: return 0;
26: }
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

The program output


C:\app>
c: address=0x1B38, content=A
x: address=0x1B36, content=7
y: address=0x1B32, content=123.45
ptr_c: address=0x1B30, content=0x1B38
*ptr_c => A
ptr_x: address=0x1B2E, content=0x1B36
*ptr_x => 7
ptr_y: address=0x1B2C, content=0x1B32
*ptr_y => 123.45
C:\app>

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Dereferencing

The value of the memory location where a pointer points can be reached again
by using an asterisks in front of the variable name. This is called dereferencing.

#include <stdio.h>
main() {
pk *pk k
Assign the address
int k=5;
&k
5
of k to pk.
int *pk;
pk = &k;
printf("Value of k is %d\n",k);
printf("Address of k is %p\n",&k);
printf("Value of pk is %p\n",pk);
printf("Address of pk is %p\n",&pk);
printf("Value referenced by pk is %d\n",*pk);
}

Value of k is 5
Address of k is 0065FDF4
Value of pk is 0065FDF4
Address of pk is 0065FDF0
Value referenced by pk is 5
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

*pk means the value of


the memory location
pointed by pk.

It is possible to change the value of the memory location pointed


by a pointer by the dereference operator (*).
Declare and initialize pk.
#include <stdio.h>
The same as writing:
main() {
int *pk; pk=&j;
int j=5;
Change the value of the
int *pk = &j;
memory location pointed by pk.
*pk = 10;
printf("Value of j is %d\n",j);
printf("Address of j is %p\n",&j);
printf("Value of pk is %p\n",pk);
printf("Address of pk is %p\n",&pk);
printf("Value referenced by pk is %d\n",*pk);
}

Value of j is 10
Address of j is 0065FDF4
Value of pk is 0065FDF4
Address of pk is 0065FDF0
Value referenced by pk is 10
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Null Pointers
A pointer is said to be a null pointer when it points to address 0.
A null pointer is assumed to be not pointing to a valid data
address.
Null pointers can be used to test whether a pointer is assigned to
a value.

For example,
int *p;
p = 0; /* Make p a null pointer */
if (p == 0) /* check whether p is a
null pointer */
printf(p is a null pointer);

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

Arrays and Pointers


Pointers can be useful when you're working with simple
variables, but they are more helpful with arrays.
An array name without brackets is a pointer to the array's
first element. Thus, if you've declared an array data[], data
is the address of the first array element.

Therefore, it is possible to assign an array variable to a


pointer directly.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

Arrays and Pointers


Note that we do not use the address
of (&) operator to get the address of
the array.

#include <stdio.h>
main() {
int arr_k[3]={2,3,7};
int *ptr_k;
ptr_k=arr_k;
printf("The first element of the array arr_k
is %d\n",*ptr_k);
}

The pointer points to the


first element of the array.

The first element of the array arr_k is 2

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

13

Arrays and Pointers


Some compilers allow pointers to be used like arrays when
referencing the elements:
#include <stdio.h>
main() {
int i, arr_k[3]={2,3,7};
int *ptr_k=arr_k;
for(i=0;i<3;i++)
printf(arr_k[%d] = %d\n",i,ptr_k[i]);
}

arr_k[0] = 2
arr_k[1] = 3
arr_k[2] = 7
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

14

Pointer Arithmetic
When you increment a pointer by 1, pointer arithmetic
automatically increases the pointer's value so that it points to the
next array element.
In other words, C knows the data type that the pointer points to
(from the pointer declaration) and increases the address stored in
the pointer by the size of the data type.
Suppose that ptr_to_int is a pointer variable to some element of
an int array. If you execute the statement ptr_to_int++; the value
of ptr_to_int is increased by the size of type int (usually 2 bytes),
and ptr_to_int now points to the next array element.
Likewise, if ptr_to_float points to an element of a type float array,
the statement ptr_to_float++; increases the value of ptr_to_float
by the size of type float (usually 4 bytes).

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Pointer Arithmetic
The following program produce exactly the same result as the
previous example.
Note that ptr_k+1 does not
necessarily point to next
byte in the memory. It
points to next element.

#include <stdio.h>
main() {
int i, arr_k[3]={2,3,7};
int *ptr_k=arr_k;
for(i=0;i<3;i++)
printf(arr_k[%d] = %d\n",i, *(ptr_k+i));
}

arr_k[0] = 2
arr_k[1] = 3
arr_k[2] = 7
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

This is different than *ptr_k+i, which


would produce 2, 3, 4 for this example.

16

Pointer Operations
Operation

Description

Assignment

You can assign a value to a pointer. The value should be an


address, obtained with the
address-of operator (&) or from a pointer constant (array name).

Indirection

The indirection operator (*) gives the value stored in the


pointed-to location.

Address of

You can use the address-of operator to find the address of a


pointer, so you can have
pointers to pointers.

Incrementing

You can add an integer to a pointer in order to point to a


different memory location.

Decrementing

You can subtract an integer from a pointer in order to point to a


different memory location.

Differencing

You can subtract an integer from a pointer in order to point to a


different memory location.

Comparison

Valid only with two pointers that point to the same array.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

17

Possible errors on pointers


Use of uninitialized pointers:
int *ptr_k;
int k=5;
*ptr_k = k;
/* Problem: I have used the pointer before having
it point to a meaningful address */
Indices that are out of range:
int j=5,arr_x[3];
int *ptr_k=arr_x;
arr_x[-1]=1; /* Index is out of range */
arr_x[j]=7; /* Index is out of range */
*(ptr_k+j) = 8;/*Pointer points to undesired
location */

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

18

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.

3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

Introduction to Scientific and Engineering


Computation (C)
BIL 104E

Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

The enum Data type


The enumerated (enum) data type can be use to declare
named integer constants. It makes the C program more
readable and easier to maintain.
Syntax is
enum tag_name{item1, item2, } var1, var2, ...;

Here tag_name is the name of the enumeration


item1, item2, ... are the names to represent integer
constants
var1, var2 ... are the variables of this newly defined
type.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

The enum Data type


For example,

enum gender{male, female} gen_student;


declares an enumarated type called gender, which can have
values male (0) or female (1), and a variable named
gen_student.
Then we can do the following:
gen_student=male; /* The same as gen_student=0; */
printf(%d\n,gen_student); /* Prints 0 on the screen */

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

#include <stdio.h>
We can define the new type in
enum gender{male,female};
beginning of the file and refer to
void PrintGender(enum gender g){ it later in the program.
if(g == male)
printf("male");
Getting an enumerated
else if(g == female)
argument of type gender. The
printf("female");
name of the argument is g.
else printf("unknown");
}
It is possible to use male and
female instead of 0 and 1,
main() {
respectively.
enum gender guser;
printf("Are you male or female?\n");
Define a variable called guser to
printf("0 for male, 1 for female\n");
represent the gender of the
scanf("%d",&guser);
user. We can use guser
printf("Your gender : ");
wherever we can use an integer.
PrintGender(guser);
printf("\n");
}
Are you male or female?
0 for male, 1 for
female
0
Your gender : male
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Type Definitions
It is possible to define an alias for a given data type using the
typedef statement. For example,
typedef

int

INTEGER;

defines an alias for the data type int called INTEGER.


Later in the program, INTEGER can be used wherever int is
used. For example,
INTEGER k, *pk;
declares two variables one of which is an integer and the other
is a pointer to integers.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Type Definitions
There are two usages of typedef:

1. It can provide a shorthand alias for data types that are


long and difficult to comprehend.
2. It brings flexibility to the program in the sense that the
types of all variables in a certain data type can be changed
easily.
For example, if we want all variables of type INTEGER
to become long integers in the program all we have to
do is to change the typedef line in the program.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Example

#include <stdio.h>
#define MAX_ELEMENTS 2
typedef char *string;
typedef string string_array[MAX_ELEMENTS];
main() {
string str="Hello World!";
string_array str_arr={"Hello","World"};
This defines a new
printf("%s\n",str);
type called string,
printf("%s\n",str_arr[0]);
which is equivalent
printf("%s\n",str_arr[1]);
to a pointer tp
}
characters.

This defines a new


type called
string_array, which
is equivalent to an
array of pointers to
characters.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

STRUCTURES
Arrays can be used to collect same type of data.

However, arrays are not suitable for collecting different


types of data.
Sometimes we handle more complex data. For
example, the data about a person may consist of the
name, surname, gender and date of birth of that
person.

In order to give reference to such data by using a single


variable, it is possible to define new data types called
structures.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

STRUCTURES
A structure can be declared by using the following
syntax:
struct struct_tag {
data_type1 variable1;
data_type2 variable2;
data_type3 variable3;
.
.
.
};
The following is an example of a structure declaration:
struct automobile {
int year;
char model[8];
int engine_power;
float weight;
};
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

STRUCTURES
After declaring a structure, you can also define structure
variables such as
struct automobile sedan, pick_up, sport_utility;
which enables defining structure variables with the same
structure of automobile.

You can also combine the structure declaration and


definition into one statement as below
struct automobile {
int year;
char model[8];
int engine_power;
float weight;
} sedan, pick_up, sport_utility;
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

10

Example

struct Complex{
double Re, Im;
}
shows a data type that consists of two components
with names Re and Im both of which are of type double.

Stucture variables can be defined by using the following


syntax:
struct struct_tag var1, var2, ;
For example,
struct Complex c;
defines a variable named c of Complex type.

? ?
Re Im

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

11

Referencing Structure Members


It is possible to give reference to components of a
structure variable by using the dot (.) operator. For
example,
5.0
?
c
c.Re = 5.0;
Re Im
causes the Re component of the variable c to become 5.0.
Components referenced in this way can be used as if they
were variables. (In printf and scanf statements, as
arguments to functions etc.) For example,
printf(%d, c.Re);
displays 5.0 on the screen.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

/* 19L01.c Access to structure members */


#include <stdio.h>

Example

main(void)
{
struct computer {
float cost;
int year;
int cpu_speed;
char cpu_type[16];
} model;
printf("The type of the CPU inside your computer?\n");
gets(model.cpu_type);
printf("The speed(MHz) of the CPU?\n");
Assigning a value
scanf("%d", &model.cpu_speed);
input by the user to
printf("The year your computer was made?\n");
scanf("%d", &model.year);
a structure variable
printf("How much you paid for the computer?\n");
scanf("%f", &model.cost);
printf("Here are what you entered:\n");
printf("Year: %d\n", model.year);
printf("Cost: $%6.2f\n", model.cost);
printf("CPU type: %s\n", model.cpu_type);
printf("CPU speed: %d MHz\n", model.cpu_speed);

Displaying the value


of structure
variables

return 0;
}

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

13

Example output

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

14

Initializing Structures
A structure can be initialized by a list of data called
initializers. The types of corresponding items in
component list and initializers should match. For
example,

struct Complex c={3.0, 5.0};


declares a complex variable c and assigns 3.0 and 5.0 to
Re and Im components, respectively.
c 3.0 5.0
Re Im

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Example
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

/* 19L02.c Initializing a structure */


#include <stdio.h>
main(void)
{
struct employee {
int id;
char name[32];
};
/* structure initialization */
struct employee info = {
1,
"B. Smith"
};
printf("Here is a sample:\n");
printf("Employee Name: %s\n", info.name);
printf("Employee ID #: %04d\n\n", info.id);
printf("What's your name?\n");
gets(info.name);
printf("What's your ID number?\n");
scanf("%d", &info.id);
printf("\nHere are what you entered:\n");
printf("Name: %s\n", info.name);
printf("ID #: %04d\n", info.id);
}

return 0;

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

16

Example Output
C:\app>19L02
Here is a sample:
Employee Name: B. Smith
Employee ID #: 0001
What's your name?
T. Zhang
What's your ID number?
1234
Here are what you entered:
Name: T. Zhang
ID #: 1234
C:\app>

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

You can also combine the


declaration, definition,
and initialization of a
structure into a single
statement.
struct employee {
int id;
char name[32];
} info = {
1,
"B. Smith"
};

17

Remarks on structures
It is possible to have arrays and other structures as
components of structures.
It is also possible to have array variables of structures.

It is possible to pass structures as arguments to


functions and functions can return structures as their
output value.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

18

Pointers to Structures

It is possible to declare pointers that can point to structure


variables. The arrow (->) operator can be used with the pointer
to directly reach the members of the structure. For example,
#include <stdio.h>
struct automobile{
int year;
char make[8], model [8];
int engpw;
float weight;
};

Defining a pointer with


structure

main() {
struct automobile mycar = {1982, "BMW",
"3.16i", 1600, 1543.5};
Assigning a structure
struct automobile *pcar;
values to the pointer
pcar = &mycar;
printf("mycar.year \t= %d\n", mycar.year);
printf("(*pcar).year \t= %d\n",(*pcar).year);

printf("pcar->year \t= %d\n",pcar->year);

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

19

Structures as arguments of functions


It is possible to pass an entire structure to a function. In
addition, a function can return a structure back to its caller. E.g.

typedef struct automobile sauto;


Instead of writing
sauto ChangeMake(sauto acar) {
struct automobile
sauto temp;
each time we can now
temp=acar;
shortly use sauto type.
printf("Current make is %s\n",
acar.make);
printf("What is the make of the car?
\n");
This function changes the make of a given car
gets(temp.make);
return temp;
and returns the result as a new car.
}
main() {
struct automobile mycar = {1982, "BMW",
"3.16i", 1600, 1543.5};
struct automobile *pcar;
pcar = &mycar;
mycar=ChangeMake(mycar);
printf("mycar.make \t= %s\n", mycar.make);
}
Current make is BMW
What is the make of the car?
Anadol
mycar.make
= Anadol

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

20

Example
#define MAX_CHARS 15
typedef char name_string[MAX_CHARS];
enum gen{male,female};
typedef enum gen type_gender;
struct structperson{
name_string name, surname;
int age;
type_gender gender;
};
typedef struct structperson person;
struct structstudent{
person individual;
name_string department;
int quiz[6];
int homework[6];
int final;
};
typedef struct structstudent student;
student studs[50];

studs

(1)

(2)

(3)

?
(i)

(50)

studs(i)

surname ?

name
individual

department

age

gender

?
?

quiz

[0] [1] [2] [3] [4] [5]

homework

[0] [1] [2] [3] [4] [5]

final

main(){
student john={ {"John","Smith",20,male}, "Computer Eng.",
{20,45,-1,-1,-1,-1},{75,-1,-1,-1,-1},-1};
printf("%s\n",john.individual.name);
printf("%d\n",john.quiz[1]);

John

45

john

J
surname S
name

individual

department

quiz
homework
final

age

20

gender

o h n \0 ? ?
? i t h \0 ?
m

C o m p u t
20
[0]

75
[0]

-1

45
[1]

-1
[1]

-1
[2]

-1
[2]

-1
[3]

-1
[3]

e
-1
[4]

-1
[4]

r
-1
[5]

-1
[5]

?
?

?
?

?
?

?
?

?
?

?
?

n g

\0

?
?

?
?

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez

2) SAMS Teach Yourself C" by T Zhang.


3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

24

Introduction to Scientific and Engineering


Computation (C)
BIL 104E

Instructor: Dr. Fuat Kucuk

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

Handling Files
In our programs so far, we have only used the standard
input, which is normally the keyboard, for receiving data
from the outer world, and the standard output, which is
normally the screen, for sending data to the outer world.
When we exit the program all the information contained in
the program (values of variables) is lost.
This means that every time we start our computer we have
to re-enter any necessary input data, re-calculate any
necessary calculations, and print out the results.
However, one of the most important characteristics of
computers is their ability to store data for later use.
The data, in general, is stored in files on hard-disks, floppydisks, magnetic-tapes, zip-drives, CD-ROMS etc.

Files can also contain program source codes (called


source code files) and machine language instructions
(called executable files).
Files that contain data to be processed by programs
are called data files.
Data files consist of units of data called records.

The FILE structure


The FILE structure is defined in stdio.h and is used to access
files. In order to reach files we first define a pointer to FILE.
For example, FILE *fptr;
Each file should be opened first before using them.
fopen() function is used for this purpose. The syntax is
file_ptr = fopen(file_name, mode);
Here file_ptr is a pointer to FILE structure, file_name is a string
consisting of the path and name of the file to be opened, and
mode is another string that determines the opening mode of the
file.
After the file is opened it can be reached via file_ptr. If fopen is
not success for any reason (for example file does not exist or the
disk is full etc) it returns NULL value.

The mode parameter is made by a combination of the characters r


(read), w (write), b (binary), a (append), and + (update).
For example,
r opens existing text file for reading
w creates a text file for writing
a opens an existing text file for appending
r+ opens an existing text file for reading or writing
w+ creates a text file for reading and writing
a+ opens or creates a text file for appending
rb opens an existing binary file for reading
wb creates a binary file for writing
ab opens an existing binary file for appending
r+b opens an existing binary file for reading or writing
w+b creates a binary file for reading and writing
a+b opens or creates a binary file for appending

Closing a file
It is a good programming practice to close any files
opened before the termination of the program. It is also
a requirement that a file has to be closed before it can
be opened again (perhaps in another mode).
This is done by using the fclose() function.
The syntax is as follows:
fclose(file_ptr);
Here, file_ptr is a pointer to a FILE that has been
opened.

Reading and Writing Text Files


fgetc(file_ptr) and fputc(ch, file_ptr) functions can be used to
read and write characters to text files. Here, ch is the character to
written to the file and file_ptr is a pointer to an opened FILE.
fgetc() returns the character read from the file.

fgets(str, n, file_ptr) and fputs(str, file_ptr) functions can be used


to read and write strings to text files. Here, str is a pointer to a
string (or a character array), file_ptr is a pointer to an opened FILE
and n is an integer that shows the maximum number of characters
to be read from the file.
It is also possible to use fprintf() and fscanf() for formatted
input/output. These are very similar to printf() and scanf()
functions, except that they require a FILE pointer as the first
argument.

Examples
This program creates a file named try.txt and writes This
text is written in a file in it.
#include <stdio.h>
Open the file in write-only mode.
main(){
FILE *fptr;
Check if any problem has
fptr = fopen("try.txt","w"); occured while openning
the file.
if(fptr == NULL){
printf("Problem in opening the
file!");
return -1;
}
fprintf(fptr,"This text is written
in a file");
fclose(fptr);
return 0;
}

This file reads the data previously written in try.txt.


#include <stdio.h>
main(){
Open the file in read-only mode.
FILE *fptr;
char buffer[255];
fptr = fopen("try.txt","r");
if(fptr == NULL){
printf("Problem in opening the
file!");
return -1;
Read at most 250 characters from
}
the file.

fgets(buffer,250,fptr);
printf("%s\n",buffer);
fclose(fptr);
return 0;

This text is written in a file

End of file
When reading data from files, it is necessary to test whether
the end of the file has been reached or not.
If fgetc() or fscanf() functions are used, they return an EOF
character when the end of the file has been reached.

If fgets() is used it returns a NULL pointer.


It is also possible to use the feof() (end of file) function to
test whether the end of the file has been reached or not.

Example 1
Write a program reads 5 integers from the keyboard and stores
them in separate lines in a file called Integers.txt. If an error
occurs in opening the file an appropriate message should be
displayed.

#include <stdio.h>
main(){
FILE *fIntegers;
int i,k;
fIntegers=fopen("Integers.txt","w");
if(fIntegers==NULL){
printf("Problem in openning the file!");
return -1;
}
for(i=0;i<5;i++) {
printf("Enter a number:\n");
scanf("%d",&k);
fprintf(fIntegers,"%6d\n",k);
}
fclose(fIntegers);
return 0;
}
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

12

If the numbers
5, 15, 344, 12, 2443
are entered from the keyboard then the file Integers.txt
will consist of the following 5 lines:
5
15
344
12
2443

Example 2
Write a program that reads 5 Integers from the first five
records of a file called Integers.txt, and then prints them on
screen. The numbers should be assumed to be in the same
format as in the the previous example. If an error occurs in
opening the file an appropriate message should be displayed.

#include <stdio.h>
main(){
FILE *fIntegers;
int i,k;
fIntegers=fopen("Integers.txt","r");
if(fIntegers==NULL){
printf("Problem in openning the file!\n");
return -1;
}
for(i=0;i<5;i++) {
fscanf(fIntegers,"%d",&k);
printf("%6d\n",k);
}
fclose(fIntegers);
return 0;
}
If the file is corrupted or it contains less than 5 records this program fails.
A better programming example would be checking for such conditions.
BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

15

Example 3
In an experiment, values of the temperature in a container is
observed at several times during a day and the results of
observations are entered from the keyboard to be saved in a file,
whose name is entered by the user.
Write a program called TemperatureReader that first reads the
name of the output file and then asks the user the time and the
corresponding temperature repetitively until the temperature
entered is 99. The time should be read as a four character string in
the hhmm format. The program should allow integer temperatures
between 99 and 250. As the information is being entered from the
keyboard, it should be written to the output file in a suitable tabular
format. In order to increase the readability of the output file, the
columns in the output file should be preceded by suitable labels
such as Time and Temp.

#include <stdio.h>
main(){
FILE *ftemp;
char filename[250];
char tm[5];
int temp;
printf("Enter the name of the file:\n");
scanf("%250s",filename);
ftemp=fopen(filename,"w");
if(ftemp==NULL){
printf("Problem in openning the file!");
return -1;
}
fprintf(ftemp,"Time \t Temp \n ---- \t ----\n");

(continues in the next slide)

do {
printf("Please enter time:\n");
scanf("%4s",tm);
do {
printf(Please enter temperature:\n");
scanf("%d",&temp);
} while(temp<-99 || temp>250);
if (temp!= -99)
fprintf(ftemp,"%4s \t %4d\n",tm,temp);
} while(temp!= -99);

fclose(ftemp);
return 0;

A sample run of the program:


Please enter the name of output
file:
Experiment.txt
Please enter time:
0910
Please enter temperature:
45
Please enter time:
0930
Please enter temperature:
55
Please enter time:
0950
Please enter temperature:
640
Please enter temperature:
64
Please enter time:
1020
Please enter temperature:
-99

Experiment.txt file
after the execution:
Time Temp
---- ---0910
45
0930
55
0950
64

A program that prints the contents of a text file.

#include <stdio.h>
main(){
FILE *ftemp;
char filename[250],buffer[80];
int flag=0;

printf("Enter the name of the file:\n");


scanf("%250s",filename);
ftemp=fopen(filename,"r");
if(ftemp==NULL){
printf("Problem in openning the file!");
return -1;
}
while(!feof(ftemp)) {
flag=fgets(buffer,80,ftemp);
if(flag != NULL)
printf("%s",buffer);
}
fclose(ftemp);

References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez

2) SAMS Teach Yourself C" by T Zhang.


3 C How to Program , Deitel & Deitel, Prentice Hall, 2007.

BIL104E INTRO. TO SCI. & ENG. COMP. (C) by Fuat KUCUK

21

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