Cdersi 1-7
Cdersi 1-7
Cdersi 1-7
SCIENTIFIC AND
ENGINEERING
COMPUTING (C)
LECTURE 1
Ders başarı kriterleri / Course success criteria
2
1 1
The
course material will be uploaded in
www.ninova.itu.edu.tr
The
homework should be uploaded in
www.ninova.itu.edu.tr
What is C?
• Readability
• Maintainability
• Portability
Each high-level language needs a compiler or an
interpreter to translate instructions written in the high-level
programming language into a machine language that a
computer can understand and execute.
In this class we will learn the C functions defined in the ANSI standart.
#include directive
Header files
Comments
The main() function
The return statement
The exit() function
The newline character (\n)
First C Program
First C Program
Let’s open our first program in
different PC!
Note that our output is « Hello C!
This is my first C program».
Comments
Now look at our first program. The first line comment is:
/* Course1.1: This is my first C program */
Line-1 starts with a combination of slash and asterisk, /*, and ends with */. In C,
/* is called the opening comment mark, and */ is the closing comment mark.
The C compiler ignores everything between the opening comment mark and
closing comment mark.
The main reason of using comments in the C is to say what the program do.
Comments
There is another way to put comments into a C program. C++
started using two slashes (//) to mark the beginning of a comment
line; many C compilers now use this convention as well.
// as the beginning mark of a comment has not been approved by
ANSI C. Make sure your C compiler supports // before you use it.
The #include Directive
Line 2 is #include<stdio.h>
This line starts with a pound sign, #, which is followed by include.
In C, #include forms a preprocessor directive. It tells to look for a file and place
the contents of that file.
In this example, include directive looks for standard input-output header file
(stdio.h) file and then place it at the location of the directive in the C.
Standard input-output header file (stdio.h) contains numerous prototypes and
macros to perform inputs or outputs (I/O) for C programs.
Header Files
The files that are included by the #include directive, like stdio.h,
They are called header files because the #include directives are almost always
placed at the start, or head of C programs.
Actually, the extension name of .h does mean “header”.
Besides stdio.h, there are more header files, such as stdlib.h, string.h, math.h and so
on.
The specific header files you need to include depend on the specific library functions.
The documentation for library functions will tell you which header file is required.
Standard
Header Files
Angle Brackets (<>)
In the second line of the programme, there are two angle brackets < and >, that are
used to surround stdio.h.
In C, the angle brackets ask the C preprocessor to look for a header file in a directory
other than the current one.
The main() Function
In line 4 there is main() in our example.
Every C program must have a main() function and every C program can only have
one main() function.
You can put the main() function wherever you want in your C program. However,
the execution of your program always starts with the main() function.
If you create other functions in your program, main () will always execute first, even if
it is at the bottom of your program file.
A program also ends when all the statements within the main() function have been
executed.
The Newline Character (\n)
In our program, main() function body has printf() function to print out the
computer screen a greeting message. Printf function is a C library function of
stdio.h file. More details about printf(), we will see in next hours.
In the printf() function, there is newline character, \n. This character is used for
moving the cursor in the next line.
The Return Statement
All functions in C can return values.
The main() function returns an integer value.
There is a statement, return 0;
It indicates that 0 is returned from the main() function and the program is terminated
normally.
The exit() Function
There is also a C library function, exit(), that can be used to end a program.
Because the exit() function is defined in a header file, stdlib.h, you have to
include the header file at the beginning of your program in order to use the
function. The exit() function itself does not return a value to your program.
Compiling
and Linking
First, a program file written in C is called source code, is made. The source
code file is compiled by a C compiler, which creates a new file. The new file is
an object file.
You cannot execute the object file. You have to finish the next step: linking.
Linking is done by invoking a special program called a linker.
A linker is used to link together the object file and the ANSI standard C library,
the executable file ends with ‘’.exe’’
Debugging
Program errors are also called bugs. Your C compiler and linker do not find any
errors in your program, but the result may not what you expect. You may need
to use a debugger.
C compilers already include a debugger software program. The debugger can
execute your program one line at a time so that you can watch closely what’s
going on with the code in each line, or so that you can ask the debugger to
stop running your program on any line.
INTRODUCTION to
PROGRAMMING
LANGUAGE (C)
LECTURE 2
Learning Structure of C Program
In this lesson we will learn more essentials in a C program, such as
i = 1;
the symbol i is assigned the constant 1. In other words, i contains the value of 1
after the statement is executed. Later, if there is another statement,
i = 10;
For example:
(2 + 3) * 10
7%4
2 + 3 * 10
For example:
i = 1;
is a statement. You might have already figured out that the statement consists of
an expression of i = 1 and a semicolon (;).
i = (2 + 3) * 10;
i = 2 + 3 * 10;
j = 6 % 4;
k = i + j;
return 0;
exit (0);
printf ("Hello.\n");
Statement Blocks
A group of statements can form a statement block. They starts with an
opening brace ({) and ends with a closing brace (}).
For(. . .) {
s3=s1 + s2;
mu1= s3*c;
remainder = sum % c;
}
Data Types and Keywords
C Keywords
There are certain words in the C language having special meanings.
You should not use the C keywords for your own variable, constant, or
function names in your programs.
Reserved Key words in C
• Reserved Keywords in C
• Keyword Description
• auto Storage class specifier
• break Statement
• case Statement
• char Type specifier
• const Storage class modifier
• continue Statement
• default Label
• do Statement
• double Type specifier
• else Statement
• enum Type specifier
• extern Storage class specifier
Reserved Key words in C
• float Type specifier
• for Statement
• goto Statement
• if Statement
• int Type specifier
• long Type specifier
• register Storage class specifier
• return Statement
• short Type specifier
• signed Type specifier
• sizeof Operator
• static Storage class specifier
• struct Type specifier
• switch Statement
Reserved Key words in C
• typedef Statement
• union Type specifier
• unsigned Type specifier
• void Type specifier
• volatile Storage class modifier
• while Statement
Data Types in C
OR
char variablename, variablename1, variablename2;
Character Constants
A character enclosed in (') single quotes is called a character constant. (")
doble quote will be used in the string of more than one character.
For example, 'a', 'A' are all character constant that have their unique numeric
values. From the ASCII character set, unique numeric values of ‘A’, ‘a’ are 65,
97 as seen below.
x= ‘A’;
x=65;
x= ‘a’;
x=97;
The important part in this part is, do not confuse x=‘H' with x=H.
float variablename;
float variablename;
float variablename1;
float variablename2;
OR
float variablename, variablename1, variablename2;
The double Data Type
A floating-point number can also be represented by another data type, called
the double data type.
In other words, you can specify a variable by the double keyword, and assign
the variable a floating-point number. Twice bit are stored for double type
numbers.
double variablename;
double variablename;
double variablename1;
double variablename2;
OR
double variablename, variablename1, variablename2;
5000=5e3 or 0.0023=2.3e-3.
Before start learning these new functions, let’s start with an idea about
standard input and output (I/O) in C.
Standard Input and Output (I/O)
In C, there are three file streams that are pre-opened for us. They are always
available for use in your programs:
• stdin—The standard input for reading.
• stdout—The standard output for writing.
• stderr—The standard error for writing error messages.
The figure shows us relation between the format string and the expressions in printf().
The format specifiers and the expressions are need to be matched in order from left to
right.
The following are most used the format specifiers in printf():
We can use the precision specifier to determine the number of decimal places for
floating-point numbers, or to specify the maximum field width for integers.
For instance, with %10.3f, the minimum field width length is specified as 10
characters long, and the number of decimal places is set to 3. (the default number
of decimal places is 6.)
For integers, %3.8 d indicates that the minimum field width is 3, and the maximum
field width is 8.
An Example
Scanf()
This function allows to enter values from the keyboard while the
program is being executed. The first argument of it is a control string
that specifies the types of the variables whose values are to be
entered from the keyboard.
The remaining arguments are the memory locations that correspond to
the specifiers in the control string. The memory locations are indicated
with the address operator (&).
An Example
INTRODUCTION to
PROGRAMMING
LANGUAGE (C)
Manipulating Data
We’ve learned some operators, such as + (addition),- (subtraction), *
(multiplication), / (division) and % (remainder). The C language has a rich
set of operators. In this lesson, we’ll learn about more operators, such as
Among the six relational operators, the >, <, >=, and <= operators have higher
precedence than the == and != operators.
Another important point is that all relational expressions produce a result of either 0
or 1. In other words, a relational expression evaluates to 1 if the specified relationship
holds. Otherwise, 0 is yielded.
Given x = 3 and y = 5, for instance, the relational expression x < y gives a result of 1.
An Example
An Example
CONDITIONAL OPERATORS
Everything Is Logical
Exp Yields
Nonzero 0
0 1
An example
X?Y:Z
The operator ?: is called the conditional operator, which is the only
operator that takes three operands. The general form of the conditional
operator is
x?y:z
Here x, y, and z are three operand expressions. x contains the test
condition, and y and z represent the two possible final values of the
expression.
If x evaluates to nonzero (logically true), then y is chosen; otherwise, z is the
result yielded by the conditional expression. The conditional operator is
used as a kind of shorthand for an if statement.
For example, the expression
x > 0 ? ‘T’ : ‘F’
evaluates to ‘T’ if the value of x is greater than 0. Otherwise, the
conditional expression evaluates to the value ‘F’.
An example
INTRODUCTION to
PROGRAMMING
LANGUAGE (C)
Working with Loops
while (expression)
statement;
An Example
The do-while Loop
or
for (expression1; expression2; expression3) {
statement1;
statement2;
.
.
}
The first time the for statement is executed, it first evaluates expression1, which is
typically used to initialize one or more variables.
The second expression, expression2, acts in the same way as the conditional
expression of do-while loop. This second expression is evaluated immediately
after expression1, and then later is evaluated again after each successful
looping by the for statement. If expression2 evaluates to a nonzero (logical true)
value, the statements within the braces are executed. Otherwise the looping is
stopped and the execution passes at the next statement after the loop.
The third expression in the for statement, expression3, is not evaluated when the
for statement is first encountered. However, expression3 is evaluated after each
looping and before the statement goes back to test expression2 again.
The following for statement contains a single statement:
• The if statement
• The if-else statement
• The switch statement
• The break statement
• The continue statement
If Statement
In C, the if statement is the most popular conditional branching statement;
The general form of the if statement is
if (expression) {
statement1;
statement2;
.
.
.
}
The braces { } form a block of statements and it is under the control of the if
statement.
If there is only one statement inside the block, the braces can be omitted. The
parentheses (), however, must be always used to enclose the conditional expression.
else {
statement_C;
statement_D;
..
The switch Statement
With the switch statement, we can use to make unlimited decisions or choices
based on the value of a conditional expression and specified cases.
The general form of the switch statement is
switch (expression) {
case constant-expression1:
statement1;
case constant-expression2:
statement2;
..
default:
statement-default;
}
An example
The break Statement
If you want to exit the switch entirely after each case label, we can
add a break statement at the end of the statement list and it follows
every case label.
An example
Breaking an Infinite Loop
We can also use the break statement to break an infinite loop.
The following are examples of infinite for and while loops:
for (;;) {
statement1;
statement2;
.
.
}
while {
statement1;
statement2;
}
An example
/* Breaking an infinite loop */
#include <stdio.h>
main() {
int c;
printf(“Enter a character:\n(enter x to exit)\n”);
while {
c = getc(stdin);
if (c == ‘x’)
break;
printf(“Break the infinite while loop. Bye!\n”);
return 0;
}
The continue Statement
When you want to stay in a loop without executing some statements
within the loop. We can use the continue statement.
The continue statement causes execution to jump to the bottom of the
loop immediately.
An example
INTRODUCTION to
PROGRAMMING
LANGUAGE (C)
Functions in the C
When you call a C function which returns a data type, the value it returns (return value) can then be
used in an expression. We can assign it to a variable, such as
int a = func();
or use it in an expression, like this
a = func() + 7;
Giving a Function a Valid Name
A function name reflects what the function can do.
For example the name of the printf() function means “print formatted
data.”
Passing Arguments to C Functions
The compiler will issue an error message if there is any argument passed to
getchar() later in a program when this function is called
Functions with a Fixed Number of
Arguments
We have seen several examples that declare and call functions with a fixed
number of arguments.
For example,
int integer_add(int x, int y)
contains the prototype of two arguments, x and y.
To declare a function with a fixed number of arguments, you need to specify
the data type of each argument.
It’s also recommended to indicate the argument names so that the compiler
can check to make sure that the argument types and names declared in a
function match with the function definition.
Prototyping a Variable Number of
Arguments
As you may remember, the syntax of the printf() function is
int printf (const char *format[, argument, ...]);
Three dots represents a variable number of arguments. In other words,
besides the first argument that is a character string, the printf() function can
take an unspecified number of additional arguments, as many as the
compiler allows. The brackets ([ and ]) indicate that the unspecified
arguments are optional.
Math Functions
Basically, the math functions provided by the C language can be classified
into three groups:
• Trigonometric and hyperbolic functions, such as cos(), acos() and cosh().
• Exponential and logarithmic functions, such as exp(), pow(), and log10().
• Miscellaneous math functions, such as ceil(), fabs() and floor().