Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Computation (C)
BIL 104E
Instructor: Dr. Fuat Kucuk
Joseph Fourier
2
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
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
10
11
Computer Organization
Main Memory
Input Devices
Output Devices
Secondary Memory
(File Storage)
12
13
14
15
16
17
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 !!!
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.
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.
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.
22
23
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.
25
BIL104E
Introduction to Scientific and Engineering
Computation (C)
Instructor: Dr. 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.
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
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.
13
Software Development
Four steps in writing a program:
Specify the problem clearly.
Analyse the problem and break it down into
smaller parts.
14
Programming practice
1
2
3
4
5
6
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
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:
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.
20
21
References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.
22
BIL104E
Introduction to Scientific and Engineering
Computation (C)
Instructor: Dr. 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
Assignments (2)
x = y+2;
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
Parentheses
*
/
%
Multiplication
Division
Remainder
+
-
Addition
Subtraction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
10
Data Types in C
Integer types
Arrays
Floating Type
Pointers
Character types
Structures
Enumeration
11
12
13
This is
equivalent to
ch=68;
#include <stdio.h>
main() {
char ch;
ch='A'+3;
printf("%c \n",ch);
}
To print character
variables we use
%c.
14
15
16
17
18
19
= =
! =
> =
< =
=>
=<
20
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;
}
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.
22
Declaring if statement
23
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
24
1, true
0, false
25
1
/*
Using if statements, relational
operators, and equality operators */
2
3
4
#include <stdio.h>
5
6
8
9
10
*/
11
12
13
14
15
16
17
18
19
20
21
22
if ( num1 == num2 ) {
printf( "%d is equal to %d\n", num1, num2 );
} /* end if */
if ( num1 != num2 ) {
23
} /* end if */
24
25
26
27
28
26
29
30
31
32
33
34
35
36
37
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
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.
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).
29
References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.
30
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.
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
9
10
11
13
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 */
if ( num1 != num2 ) {
printf( "%d is not equal to %d\
%d\n",
n", num1, num2 );
} /* end if */
24
25
26
27
28
return 0;
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
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");
}
Note that
since there
are only one
statements in
statement
blocks we did
not have to
use the
braces, {}.
10
11
12
13
14
Sample
Explanation
expression
++
++a
++
a++
--
--b
--b
--
b--
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
17
2
2
2
2
x
x
x
x
1
2
3
4
=
=
=
=
2
4
6
8
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;
19
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
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
1st loop
count
4
2nd loop
count
6
3rd loop
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
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 (i=7;i<3;i--)
24
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.
27
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)
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)
>
>=
!=
?:
=
+=
-=
*=
/=
%=
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
10
11
12
13
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.
15
16
17
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]
}
19
Example
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
22
23
24
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");
}
}
27
References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
28
12
12
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
1.200
12.340
12.346
123.456
123.457
011
Zero
addition
Rounding
up!
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;
10
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
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
13
Analysis:
First the angle should be read and assigned a variable (angle).
Then the angle should be converted to radians (x).
14
#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
16
17
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
19
20
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
23
References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.
24
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,
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
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.
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
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);
11
12
#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);
}
13
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).
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
16
Pointer Operations
Operation
Description
Assignment
Indirection
Address of
Incrementing
Decrementing
Differencing
Comparison
Valid only with two pointers that point to the same array.
17
18
References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
2) SAMS Teach Yourself C" by T Zhang.
19
#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;
Type Definitions
There are two usages of typedef:
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.
STRUCTURES
Arrays can be used to collect same type of data.
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.
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.
? ?
Re Im
11
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:
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);
return 0;
}
13
Example output
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,
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:
return 0;
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>
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.
18
Pointers to Structures
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);
19
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
homework
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
24
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.
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.
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;
}
fgets(buffer,250,fptr);
printf("%s\n",buffer);
fclose(fptr);
return 0;
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.
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");
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;
Experiment.txt file
after the execution:
Time Temp
---- ---0910
45
0930
55
0950
64
#include <stdio.h>
main(){
FILE *ftemp;
char filename[250],buffer[80];
int flag=0;
References:
1) Introduction to Scientific and Engineering Computation
(BIL104E), lecture notes by M. T. Sylemez
21