Nothing Special   »   [go: up one dir, main page]

Cdersi 1-7

Download as pdf or txt
Download as pdf or txt
You are on page 1of 187

INTRODUCTION to

SCIENTIFIC AND
ENGINEERING
COMPUTING (C)
LECTURE 1
Ders başarı kriterleri / Course success criteria

Ödev (Homework) Arasınav (Midterm) Final

2
1 1

30% 30% 40% 100%

Final sınavına giriş şartı en az 2 ödevin teslim edilmesidir.


For attendance Fınal Exam students have to submit at least 1 homeworks.
Course Informatıons

 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?

 C is a programming languages. It was developed in 1972 by Dennis


Ritchie.

 C is a high level Programming and most popular programming


languages.
High-level programming languages, including C, have the
following advantages:

• 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.

 According to this, we need compiler for writing our


programs. Some compilers are, Dev C++, Visual Studio,
JetBrains Clion etc.

 Programs written in C can be reused. You can save parts of your C
programs into a library file. These files are known as header files.

 You invoke them your next programming project by including the


library file.

 These library files are helpful benefit especially in complex


programming.

 The C programming is also a global programming language which


can be easily understood by other programmers.
 C is a relatively small programming language. You don’t have to
remember many C keywords or commands before you start to write
programs.

 Although C is a high level language, C allows you to get control of


computer hardware and peripherals. Because of that C language
is sometimes called low level programmin language.

 Many other high-level languages have been developed based on


C. For instance, Pearl, java, etc. Learning them becomes much
easier if you already know C.d the lowest high-level programming
language.
The ANSI C Standard
 Because of C might lose its portability, a group of compiler vendors and
software developers of American National Standards Institute (ANSI) builds a
standard for the C language in 1983.

 ANSI standard is helping to programmers for communication in same


language like English grammer rules or metric measurement systems.

 In this class we will learn the C functions defined in the ANSI standart.

 We will use Dev C++ compiler


Using Compiler
Using Compiler
Using Compiler
Using Compiler
Basics of C program
Your first programme will probably include

 #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

• Constants and variables


• Expressions
• Statements
• Statement blocks

data types in C such as


• Char data type
• Int data types
• Float data type
• Double data type
Constant and Variables
As you guess, a constant is a value and it never changes. A variable, on the
other hand, can be used to present different values.
You can see many examples in which constants and variables are in the same
statement. For instance, consider the following:

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;

after it is executed, i is assigned the value of 10. Because i can contain


different values, it’s called a variable in the C language.
Expressions
An expression is a combination of constants, variables, and operators.

For example:

(2 + 3) * 10

The final result of the expression is 50.

Similarly, the expression 10 * (4 + 5) yields 90.


Expressions
Operators
You might already be familiar with all the arithmetic operators,
except the remainder (%) operator. % is used to obtain the
remainder of the first operand divided by the second operand.
For instance, the expression

7%4

yields a value of 3 because 4 goes into 7 once with a remainder


of 3. The remainder operator, %, is also called the modulus
operator.
Among the arithmetic operators, the multiplication, division, and
remainder operators have a higher precedence than the
addition and subtraction operators. For example, the expression

2 + 3 * 10

yields 32, not 50, because of the higher precedence of the


multiplication operator. 3 * 10 is calculated first, and then 2 is
added into the result of the multiplication.
Identifiers
Names of constant, variables, functions can be defined as identifiers.

The following rules can be use to make a valid identifier.

• Characters A through Z (uppercase letter) and a through z


(lowercase letter).
• Digit characters 0 through 9 (but these can not be used as the first
character of an identifier).
• The underscore character (_).

Examples; stop_sign, Loop3, and _pause are all valid identifiers.


The following are illegal characters; that is, they do not meet the above
set of rules for identifiers:

• C arithmetic signs (+, -, *, /).


• Period, or dot character (.).
• Apostrophes (‘) or quotes (“).
• Any other special symbols such as *, @, #, ?, and so on.

For examples; 4flags, sum-result, method*4, and what_size?


They are not legal identifiers.
Statements
A statement is a complete instruction ending with a semicolon. You can turn an
expression into a statement by simply adding a semicolon at the end of the
expression.

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 (;).

Here are some other examples of statements:

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 (}).

A statement block is treated as a single statement by the C compiler.

For instance, the following:

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.

 They are reserved words and called C keywords.

 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

There are four data types in C programming. These are:

• Char data type


• Integer data type
• Float data type
• Double data type
The char Data Type
Char data type represents a single character.
For example A and a are characters but 5 is not.
But a computer can only store numeric code, so the characters such as A, Z, b
have different unique numeric code.
The ASCII (American Standard Code for Information Interchange) codes are
standard codes to represent characters.
The orijinal ASCII character set has only 128 characters.
The Character Variables
A variable that can represent different characters is called a character variable.

Declaration format of character variable is :


char variablename;

If more than one variable will be declared, the format is;


char variablename;
char variablename1;
char variablename2;

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.

x=‘H' assigns the numeric value of character H to variable x. However x=H,


assigns whatever value is H into variable x.
The Escape Character
The escape character is used in the C language to tell the computer that a special
character follows. A character with starting (\) has a unique ASCII numeric value.
For example, we used \n (known as newline character) for breaking a message into
two pieces before.
There are also some other special characters in the C language.
Printing Characters and
format specifiers %c
Printing Characters and
format specifiers %c
The int Data Type
Integer numbers are called as whole numbers. They have no fractional part of
decimal point.
According to compiler, the integer range is from 2147483647 to -2147483648 or
32767 to -32768.

Declaration of integer variables is :


int variablename;

If more than one variable will be declared, the format is;


int variablename;
int variablename1;
int variablename2;
OR
int variablename, variablename1, variablename2;
The Numeric Values of Characters
and format specifier %d
The float Data Type
The floating-point number is another data type in the C language which
contains a decimal point such as 3.14 or -2.44.
The floating-point number keyword float in C language.
The range of floating number in C programming plus or minus 1.0x10 ^37.

Declaration of float variables is :

float variablename;

If more than one variable will be declared, the format is;

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.

Declaration of double variables is :

double variablename;

If more than one variable will be declared, the format is;

double variablename;
double variablename1;
double variablename2;

OR
double variablename, variablename1, variablename2;

Format specifier %f is used like floating point number.


An Example of Float vs Integer
The double Data Type
Using Scientific Notation
In scientific notation, a number can be represented by the combination
of the mantissa and the exponent like

5000=5e3 or 0.0023=2.3e-3.

Format specifier, %e or %E, is used to format a floating-point number in


scientific notation.

The usage of %e or %E in the printf() function is the same


as %f.
INTRODUCTION to
PROGRAMMING
LANGUAGE (C)
LECTURE 3
Standard Input and Output Functions
• The getc() function
• The putc() function
• The getchar() function
• The putchar() function

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.

Usually, the standard input (stdin) file stream links to keyboard.


The standard output (stdout) and the standard error (stderr) file streams point
to screen.
We’ve already used stdout. When we called the printf() function in the last
lessons, we were actually sending the output to the default file stream, stdout,
which points to your screen.
We’ll learn more on stdin and stdout in this class.
Understanding Standard I/O
The C language provides many functions to manipulate file reading and
writing input and output. The header file stdio.h contains these functions so it
should be included in a program when we use them.
Getting Input From the User

Typing on the keyboard is default way to input information into


computers.
The C language has several functions to tell the computer to read
input from the user (typically through the keyboard.)
This lesson we will learn the getc() and getchar() functions.
The getc() function
The getc() function reads the next character from a file stream, and returns
the character as an integer.
An Example
An Example
The getchar() function

The C language provides another function, getchar(), it


performs a similar function to getc(). More precisely, the
getchar() function is equivalent to getc(stdin).
An Example
An Example
Printing Output on the Screen
In the C, getc() and getchar() for reading, there are other two
functions, putc() and putchar() for writing.
The putc() Function
The putc() function writes a character to the specified file stream,
which is the standard output pointing to your screen.
An Example
An Example
The putchar()

The putchar() can also be used to put a character on the screen.


The only difference between the two functions, putchar() needs only one
argument to contain the character.
We don’t need to specify the file stream because the standard output (stdout)
is set as the file stream to putchar().
Putchar()
Putchar()
The printf() function

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():

 %c The character format specifier.


 %d The integer format specifier.
 %i The integer format specifier (same as %d).
 %f The floating-point format specifier.
 %e The scientific notation format specifier (note the lowercase e).
 %E The scientific notation format specifier (note the uppercase E).
 %s The string format specifier.
 %x The unsigned hexadecimal format specifier (note the lowercase x).
 %X The unsigned hexadecimal format specifier (note the uppercase X).
 %p Displays the corresponding argument that is a pointer.
 %% Outputs a percent sign (%).
Specifying Minimum Field Width
The C language allows us to add an integer between the percent sign
(%) and the letter in a format specifier.
For example, in %9f, 9 is a minimum field width specifier that ensures
that the output is at least 9 character spaces wide.
This is especially useful when printing out a column of numbers.
An Example
Aligning Output
All output is placed on the right edge of the field, as long as the field
width is longer than the width of the output. You can change this and force
output to be left-justified.
We need to prefix the minimum field specifier with the minus sign (-).
For example, %-10d specifies the minimum field width as 10, and justifies the
output from the left edge of the field.
Aligning Output
Using the Precision Specifier
We can put a period (or called dot) . and an integer right after the minimum field
width specifier. The combination of them makes up a precision specifier.

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

• Arithmetic assignment operators


• Unary minus operator
• Increment and decrement operators
• Cast operator
• Relational operators
• Conditional Operators (Logical operators)
Assignment Operator(=)
The sign of equal is called an assignment operator. We’ve already used it.
The form to use an assignment operator is
left-hand-operand = right-hand-operand;
The value of the right-hand-operand to be assigned (or written) to the memory location of
the left-hand-operand. So, after the assignment, left-hand-operand will be equal to the
value of right-hand-operand.
For example, the statement a = 5;
writes the value of the right-hand operand (5) into the memory location of the integer
variable a (which is the left-hand operand in this case).
b = a = 5;
assigns 5 to the integer variable a first, and then to the integer variable b. After the
execution of the statement, both a and b contain the value of 5.
An expression such as 6 = a, will not work.
The = operator always works from right to left; therefore the value on the left must be some
form of a variable receiving the data from the expression on the right.
Don’t confuse the assignment operator (=) with the relational operator == The == operator is
introduced later.
C ombining Arithmetic Operators with =
Given two integer variables, x and y, how do we assign the addition of x and y to another
integer variable, z ?
By using the assignment operator (=) and the addition operator (+), we wil get this statement:
z = x + y;
Now, consider the same example again. This time, instead of assigning the result to the third
variable, z, let’s write the result of the addition back to the integer variable, x:
x = x + y;
Remember, the = operator always works from right to left, so the right side will be evaluated first.
Here, on the right side of the assignment operator (=), the addition of x and y is executed; on
the left side of =, the previous value of x is replaced with the result of the addition from the right
side.
The C language gives you a new operator, +=, to do the addition and the assignment together.
Therefore, you can rewrite the statement x = x + y; as
x += y;
The combinations of the assignment operator (=) with the arithmetic operators, +, -, *, /, and %,
give we another type of operators—arithmetic assignment operators:
C ombining Arithmetic Operators with =
Operator Description
+= Addition assignment operator
-= Subtraction assignment operator
*= Multiplication assignment operator
/= Division assignment operator
%= Remainder assignment operator

The following shows the equivalence of statements:


x += y; is equivalent to x = x + y;
x -= y; is equivalent to x = x - y;
x *= y; is equivalent to x = x * y;
x /= y; is equivalent to x = x / y;
x %= y; is equivalent to x = x % y;
z = z * x + y;
is not equivalent to the statement
z *= x + y;
because
z *= x + y
multiplies z by the entire right-hand side of the statement, so the result
would be the same as
z = z * (x + y);
An Example
Getting Negations of Numeric
In order to change the sign of a number, you can put the minus operator (-) right before
the number.
The - symbol used in this way is called the unary minus operator.
Don’t confuse the unary minus operator with the subtraction operator, although both
operators use the same symbol. For instance, the following statement:
z = x - -y; is the same as this statement:
z = x - (-y);
or this one:
z = x + y;
Incrementing or Decrementing by One
The increment and decrement operators are very handy to use when you want to
add or subtract 1 from a variable.
The symbol for the increment operator is ++.
The decrement operator is --.
For example
t x = x + 1; as ++x;, or
x =x - 1; with --x;.
Actually, there are two versions of the increment and decrement operators. In the
++x; statement, where ++ appears before its operand, the increment operator is
called the preincrement operator. This refers to the order in which things happen:
the operator first adds 1 to x, and then yields the new value of x. Likewise, in the
statement --x;, the predecrement operator first subtracts 1 from x and then yields
the new value of x.
If you have an expression like x++, where ++ appears after its operand,
you’re using the post-increment operator. Similarly, in x--, the decrement
operator is called the postdecrement operator.

For example, in the statement y = x++;, y is assigned the original value of x


first, then x is increased by 1. The post-decrement operator has a similar
story. In the statement y = x--; the assignment of y to the value of x takes
place first, then x is decremented.
An Example
Using the Cast Operator

We can convert the data type of a variable, expression, or constant to a


different one by prefixing the cast operator. This conversion does not change
the operand itself; When the cast operator is evaluated, it yields the same
value (but represented as a different type), which you can then use in the rest
of an expression.

The general form of the cast operator is (data-type) x


RELATIONAL OPERATORS
Greater Than or Less Than
There are six types of relations between two expressions: equal to, not equal to,
greater than, less than, greater than or equal to, and less than or equal to.
The C language provides these six relational operators:
Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
All the relational operators have lower precedence than the arithmetic operators.
Therefore, all arithmetic operations on either side of a relational operator are carried
out before any comparison is made. If you want to operate them first,you should use
parentheses to enclose them.

Among the six relational operators, the >, <, >=, and <= operators have higher
precedence than the == and != operators.

For example, the expression


x * y < z + 3 is interpreted as
(x * y) < (z + 3)

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

There are three logical operators in the C language:

• && The logical AND operator


• || The logical OR operator
• ! The logical NEGATION operator
The first two, the AND and OR operators, are binary operators; that is, they
both take two operands (one to the left and one to the right of the
operator).
The Logical AND Operator (&&)
The logical AND operator (&&) is used to evaluate the truth or falsity of a pair of
expressions. If either expression evaluates to 0 (that is, logically false), the operator
yields a value of 0. Otherwise, if — and only if — both operand expressions evaluate
to nonzero values, the logical AND operator yields a value of 1 (logically true).
A general format of the logical AND operator is:
exp1 && exp2
where exp1 and exp2 are two operand expressions evaluated by the AND operator.
A good way to understand the AND operator is to look at a table that shows the
values yielded by the AND operator depending on the possible values of exp1 and
exp2. See the truth table of the AND operator.

Exp1 Exp2 Yields


Nonzero Nonzero 1
0 Nonzero 0
Nonzero 0 0
0 0 0
An example
The Logical OR Operator (||)
The logical OR operator (||) yields a value of 1 whenever one or both
of the operand expressions evaluates to nonzero (logically true). The
|| operator yields 0 only if both operand expressions evaluate to 0
(false).
A general format of the logical OR operator is:
exp1 || exp2
where exp1 and exp2 are two operand expressions evaluated by the
OR operator. See the truth table of the OR operator

Exp1 Exp2 Yields


Nonzero Nonzero 1
0 Nonzero 1
Nonzero 0 1
0 0 0
An example
The Logical NEGATION Operator (!)
The logical negation operator (!) is a unary operator; that is, it only takes
one operand (the expression to its right). If the operand evaluates to any
nonzero value, the ! operator yields 0 (logically false); only when the
operand expression evaluates to 0, does the operator yield 1 (logically
true).
The general format of using the logical NEGATION operator is:
! (expression)
The truth table of the NEGATION operator is shown in the Table below.
The Values Returned by the ! Operator

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

Three statements in C are designed for looping:


• The while statement
• The do-while statement
• The for statement
The following sections we will explore these statements.
The while Loop
The purpose of the while keyword is to execute a statement over and over while a
given condition is true. When the condition of the while loop is no longer logically true,
the loop terminates and program execution passes the next statement following the
loop.

The general form of the while statement is

while (expression)
statement;
An Example
The do-while Loop

However, in this section, we will see another statement used for


looping, do-while, which puts the expression at the bottom of the loop.
In this way, the statements in the loop are guaranteed to be executed at
least once before the expression is tested. Note that statements in a while
loop are not executed at all if the conditional expression evaluates to zero
after the first time execution.
The general form for the do-while statement is
do {
statement1;
statement2;
.
.
.
} while (expression);
İn Here, the statements inside the statement block are executed once, and
then expression is evaluated to determine whether the looping is to
continue. If the expression evaluates to a nonzero value, the do-while loop
continues; otherwise, the looping stops and execution proceeds to the next
statement following the loop. Note that the do-while statement ends with a
semicolon, which is an important difference from the if and while
statements.
An Example
Looping Under the for Statement
The general form of the for statement is

for (expression1; expression2; expression3) {


statement;
}

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:

for (i=0; i<8; i++)


sum += i;

In the C language, there is a special statement called the null


statement. A null statement contains nothing but a semicolon. In other
words, a null statement is a statement with no expression. We will see
later it.
Using Complex Expressions in a for
Statement
The C language allows you to use the comma operator to combine multiple
expressions into the three parts of the for statement.
For example, the following form is valid in C:
for (i=0, j=10; i!=j; i++, j--){
/* statement block */
}
Here, in the first expression, the two integer variables i and j are initialized,
respectively, with 0 and 10 when the for statement is first encountered. Then, in the
second field, the relational expressions i!=j is evaluated and tested. If it evaluates to
zero (false), the loop is terminated. After each iteration of the loop, i is increased by 1
and j is reduced by 1 in the third expression. Then the expression i!=j is evaluated to
determine whether or not to execute the loop again.
An example
Nested Loop
We can put a loop (an inner loop) inside another one (an outer loop)
to make nested loops.
When the program reaches an inner loop, it will run just like any other
statement inside the outer loop.
An example
INTRODUCTION to
PROGRAMMING
LANGUAGE (C)
Controlling Program Flow
In this lesson we’ll learn about the control flow statements such as

• 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.

For example, the following expression:


if (x > 0.0)
printf(“The square root of x is: %f\n”, sqrt);
An example
The if-else Statement
We will often want the computer to execute an alternate set of statements when the
conditional expression of the if statement evaluates to logically false.
As an expansion of the if statement, the if-else statement has the following form:
if (expression) {
statement1;
statement2;
..
}
else {
statement_A;
statement_B;
..
}
An example
Nested if Statements
In many cases, a program has to make a series of related decisions. For this purpose, we can use nested if
statements.
if (expression) {
statement1;
statement2;
..
}
else if {
statement_A;
statement_B;
..
}

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

Functions are the building blocks of C programs. Functions are useful


because we can call them over and over from different points in our
program.
We have already seen the main() function, as well as two C library
functions such as printf() and exit().
Structure of Functions in the C
Determining a Function’s Type
The function type is going to return after its execution.

We have learned that the default function type of main() is int.

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

Pieces of information passed to functions are known as arguments.


The argument of a function is placed between the parentheses that
immediately follow the function name.
If no information needs to be passed to a function, we just leave the
argument field between the parentheses blank.
For example,
The main() function has no argument, so the field between the
parentheses following the function name is empty.
The Beginning and End of a Function
Braces are used to mark the beginning and end of a function. The
opening brace ({) signifies the start of a function body as the closing
brace (}) marks the end of the function body.

We can think of it as to use braces with functions, because a function


consists of one or several statements.
The function body in a function is the place that contains variable
declarations and other C statements.
Any variable declarations must be placed at the beginning of the
function body.
If your function body contains variable declarations, they must all be
placed first, before any other statements.
An example
Making Function Calls
Declaring Functions
As we know from last classes, we have to declare or define a variable
before using it.
It is also true for functions. In C, you have to declare or define a function
before you can call it.

A function declaration is not a function definition. If a function definition is


placed in our source file before the function is first called, we don’t need to
make the function declaration. Otherwise, the declaration of a function
must be made before the function is invoked.
For example, We’ve used the printf() function in almost every sample
program. Each time, I had to include a header file, stdio.h, because
the header file contains the declaration of printf(), which indicates to
the compiler the return type and prototype of the function. The
definition of the printf() function is placed somewhere else.
Prototyping Functions

There are three cases regarding arguments passed to functions.

 The first case is that functions take no argument;


 The second one is that functions take a fixed number of arguments;
 The third case is that functions take a variable number of
arguments.
Functions with No Arguments
For instance, the C library function getchar() does not need any arguments.
int c;
c = getchar();

In C, the declaration of the getchar() function can be something like this:


int getchar(void);

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().

The header file math.h should be included in C program before use


any math functions defined in this header file.
Usage of Trigonometric Functions
The syntax for the sin() function is
#include <math.h>
double sin (double x);
Here, the double variable x contains the value of an angle in radians.

The syntax for the cos() function is


#include <math.h>
double cos(double x);
Here, the double variable x contains the value of an angle in radians.
Usage of Trigonometric Functions

The syntax for the tan() function is


#include <math.h>
double tan(double x);
Here, the double variable x contains the value of an angle in radians.
An Example
Calling of pow() and sqrt()
The syntax for the pow() function is
#include <math.h>
double pow (double x, double y);
The value of the double variable x is raised to the power of y.

The syntax for the sqrt() function is


#include <math.h>
double sqrt(double x);
The sqrt() function returns the non-negative square root of x in the
double data type. An error occurs if x is negative.
An Example
#include <stdio.h>
#include <math.h>
main() {
double x, y, z;
x = 64.0;
y = 3.0;
z = 0.5;
printf(“pow(64.0, 3.0) returns: %7.0f\n”, pow(x, y));
printf(“sqrt(64.0) returns: %2.0f\n”, sqrt);
printf(“pow(64.0, 0.5) returns: %2.0f\n”, pow(x, z));
return 0;
}
An Example

pow(64.0, 3.0) returns: 262144


sqrt(64.0) returns: 8
pow(64.0, 0.5) returns: 8

You might also like