Professional Documents
Culture Documents
INTRODUCTION
Dr. Barış ATA
CEN111 Algorithms and Programming I
■ Fall 2022-2023
■ This course aims to teach students the basics of computer programming using C
Programming Language.
■ This course focuses on
– Algorithm design tools: flowcharts, pseudocodes
– C programming language primitives
– I/O functions
– Operations
– Conditions
– Loops
– Functions
– Arrays
Textbooks
■ C Programlama Dili
– Rifat Çölkesen
■ Hardware
– the actual computer equipment
■ Software
– the set of programs associated with a computer
Computers
■ Program
– a list of instructions that enables a computer to perform a specific task
■ Binary number
– a number whose digits are 0 and 1
Computer Hardware
■ Main Memory
■ Secondary Memory
■ Central Processing Unit
■ Input Devices
■ Output Devices
Memory
■ Memory cell
– an individual storage location in memory
■ Address of a memory cell
– the relative position of a memory cell in the computer’s main memory
■ Contents of a memory cell
– the information stored in a memory cell, either a program instruction or data
Memory
00101100
Byte
Memory
■ Secondary storage
– units such as disks or flash drives that retain data even when the power to the
drive is off
■ Disk
– thin platter of metal or plastic on which data are represented by magnetized
spots arranged in tracks
■ Optical drive
– device that uses a laser to access or store data on a CD or DVD or Blu-ray Disk
■ Flash drive
– device that plugs into USB port and stores data bits as trapped electrons
Central Processing Unit
■ Cursor
– a moving place marker that appears on the screen
■ Function keys
– special keyboard keys used to select a particular operation; operation selected
depends on program being used
■ Mouse, touchpad
– input devices that move a cursor on the computer screen to select an
operation
Computer Software
■ Operating System
■ Application Software
■ Computer Languages
■ Executing a Program
Operating System
■ Application
– software used for a specific task such as word processing, accounting,
database management, playing a game, or checking the weather forecast
■ Install
– make an application available on a computer by copying it to the computer’s
hard drive
Computer Languages
■ Machine language
– binary number codes understood by a specific CPU
■ Assembly language
– mnemonic codes that correspond to machine language instructions
■ High-level language
– machine-independent programming language that combines algebraic
expressions and English symbols
Executing a Program
■ Compiler
– software that translates a high-level language program into machine language
■ Source file
– file containing a program written in a high-level language; the input for a
compiler
■ Syntax
– grammar rules of a programming language
■ Object file
– file of machine language instructions that is the output of a compiler
Executing a Program
■ Linker
– software that combines object files and resolves cross-references to create an
executable machine language program
■ Integrated development environment (IDE)
– software package combining a word processor, compiler, linker, loader, and
tools for finding errors
The Software Development Method
22
CEN111
ALGORITHMS
Introduction
■ Problem
■ Problem Solving
Algorithms
■ Implementation phase
– implement the program in some programming language
Algorithms
■ Unambiguous
■ Executable
■ Ordered
Algorithms
■ Start - End
■ Goto
■ Set, Initialize
■ Read, Get
■ Print, Write, Display
Assignment
– C=A+B
– R=R+1
Mathematical Operators
■ Sequence
■ Branching (Selection)
■ Loop (Repetition)
Relational Operators
■ Determine wheter the the student passed or failed according the entered GPA. To
pass, GPA must be greater than or equal to 60.
var: gpa
1. Start
2. Get gpa
3. If gpa>=60
print "Passed"
else
print "Failed"
4. End
Algorithms
■ Find the greater of two numbers
var: number1,number2,max
1. Start
2. Get number1
3. Get number2
4. If number1>number2
max=number1
else
max=number2
5. Print max
6. End
Logical Operators
var: a,b,c,max
1. Start
2. Get a,b,c
3. If a>=b and a>=c then max=a
4. If b>=a and b>=c then max=b
5. If c>=a and c>=b then max=c
6. Print max
7. End
Structures
■ Sequence
■ Branching (Selection)
■ Loop (Repetition)
Algorithms
■ Find odd numbers between 1 to 10
var: counter
1. Start
2. counter=1
3. Print counter
4. counter=counter+2
5. If counter<=10 then go to step 3
6. End
Algorithms
■ Find odd numbers between 1 to 10
var: counter
1. Start
2. counter=1
3. If counter%2=1 then print counter
4. counter=counter+1
5. If counter<=10 then go to step 3
6. End
Flowchart
■ Flowchart is a diagram which visually presents the flow of data through processing
systems.
■ Once the flowchart is drawn, it becomes easy to write the program in any high level
language.
Flowchart Symbols
■ Terminal
■ Flow lines
■ Process
■ Input/output
■ Used for any I/O operation. Indicates that the computer is to obtain data or output
results.
Input Output
Flowchart Symbols
■ Decision
■ Connector
■ Allows the flowchart to be drawn without intersecting lines or without a reverse flow.
Flowchart Symbols
■ Predefined process
END
Exercise
■ Find the greater of two numbers
var: number1,number2,max
1. Start
2. Get number1
3. Get number2
4. If number1>number2
max=number1
else
max=number2
5. Print max
6. End
Homework
■ Using flowcharts, write an algorithm to read three numbers then display the
smallest.
CEN111
ALGORITHMS II
Basic Control Structures
■ Sequence
■ Selection
■ Loop
Basic Control Structures
■ Sequence
– Steps that execute in sequence are
represented by symbols that follow
each other top to bottom or left to
right.
Basic Control Structures
■ Selection
– Once the condition is evaluated, the
control flows into one of two paths.
■ Loop
– Either the processing repeats or the
control leaves the structure.
Basic Control Structures
■ Loop
– Either the processing repeats or the
control leaves the structure.
Algorithms
OVERVIEW OF C
History of C
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
The Programming Process
#include <stdio.h>
#include <stdio.h>
■ SYNTAX:
#include <standard header file>
■ EXAMPLES:
#include <stdio.h>
#include <math.h>
Function main
■ SYNTAX:
int main(void)
{
function body
}
The printf Function
printf(“Hello world!\n”);
return 0;
■ Valid Identifiers
letter_1, letter_2, inches, CENT_PER_INCH,
Hello, variable
■ Invalid Identifiers
1Letter double int TWO*FOUR joe’s
Variable Declarations
■ Variable
– a name associated with a memory cell whose value can change
■ Variable declarations
– statements that communicate to the compiler the names of
variables in the program and the kind of information stored in each
variable
– Variables must be declared before use, a syntax (compile-time)
error if these are violated
■ Every variable has a name, a type, a size and a value
Basic Datatypes in C
■ Integer int
■ Character char
■ Floating Point float
■ Double precision double
floating point
■ Datatype modifiers
– signed / unsigned (for int and char)
– short / long
Basic Datatypes in C
■ signed char (8 bits) -127 to +127
■ unsigned char 0 to 255
■ short int (16 bits) -32,767 to +32,767
■ unsigned short int 0 to 65,535
■ int (32 bits) -2,147,483,647 to +2,147,483,647
■ unsigned int 0 to 4,294,967,295
■ long int (32-64 bits) -2,147,483,647 to +2,147,483,647
■ unsigned long int 0 to 4,294,967,295
■ float ~10^-37 to ~10^38
■ double ~10-^307 to ~10^308
■ long double ~10^-4931 to ~10^4932
Variable Declarations
#include<stdio.h>
#define PI 3.14
int main(void)
{
float area;
float radius=3;
area=PI*radius*radius;
return 0;
}
Operators
■ Arithmetic operators
■ Assignment operator
■ Logical operators
Arithmetic Operators
Arithmetic Operator Meaning Example
+ addition 5 + 2 is 7
5.0 + 2.0 is 7.0
– subtraction 5 – 2 is 3
5.0 – 2.0 is 3.0
* multiplication 5 * 2 is 10
5.0 * 2.0 is 10.0
/ division 5.0 / 2.0 is 2.5
5 / 2 is 2
% remainder 5 % 2 is 1
Arithmetic Operators
Assignment Operator
■ Postfix Increment/Decreement
int a=3;
a++; \\ a=a+1
■ The value of the postfix increment expression is determined
before the variable is increased
x=a++;
1. x=a;
2. a=a+1;
Increment and Decrement Operators
■ Prefix Increment/Decreement
int a=3;
++a; \\ a=a+1
■ The effect takes place before the expression that contains
the operand is evaluated
x=++a;
1. a=a+1;
2. x=a;
Increment and Decrement Operators
/*** increment and decrement expressions ***/
#include <stdio.h>
int main(void)
{
int a =0 , b = 0, c = 0;
a = ++b + ++c;
a = b++ + c++;
a = ++b + c++;
a = b-- + --c;
return 0;
}
Compound Assignment Operator
■ sum=sum+x;
■ can be abbreviated
– sum+=x;
■ input operation
– an instruction that copies data from an input device into
memory
■ output operation
– an instruction that displays information stored in memory
■ input/output function
– a C function that performs an input or output operation
■ function call
– calling or activating function
The printf Function
scanf(“%d”, &number);
Input and Output
#include <stdio.h>
int main()
{
int a,b;
scanf("%d %d",&a,&b);
printf("%d",a+b);
return 0;
}
Exercise
■ Sequence structures:
– Programs executed sequentially by default
■ Selection structures:
– if, if…else, and switch
■ Repetition structures:
– while, do…while and for
Control Structures
■ control structure
■ compound statement
– a group of statements bracketed by { and } that are executed
sequentially
Compound Statement
{
statement;
statement;
.
.
.
statement;
}
Control Structures
?
Conditions
rest_heart_rate > 75
Relational and Equality Operators
■ The expressions
– a == b is a test for equality.
– a = b is an assignment expression
Logical Operators
■ logical expressions
– an expression that uses one or more of the logical operators
■ && (and)
■ || (or)
■ ! (not)
Logical Operators
Expression Value
!5 0
!!5 1
!(6 < 7) 0
!6 < 7 1
!(3-4) 0
Operator Precedence
Operator Precedence
() highest (evaluated first)
! + - (unary operator)
* / %
+ -
< <= >= >
== !=
&&
||
= lowest (evaluated last)
Short-Circuit Evaluation
■ For the expressions that contain the operands of && and ||, the
expression process stops as soon as the outcome true or false is
known.
■ Suppose expr1 is 0.
– expr1 && expr2 = 0 (expr2 will not be evaluated.)
■ Suppose expr1 is nonzero.
– expr1 || expr2 = 1 (expr2 will not be evaluated.)
SELECTION STRUCTURE
making decisions
Flowcharts of if Statements with
Two Alternatives and One Alternative
The if Selection Statement
FORM: if ( condition )
statement_T ;
EXAMPLE: if (x > 0)
prod = prod * x;
FORM: if ( condition )
statement_T ;
else
statement_F ;
EXAMPLE: if (x > 0)
printf("positive\n");
else
printf("negative\n");
INTERPRETATION: If condition evaluates to true ( a nonzero value), then
statement_T is executed and statement_F is skipped; otherwise, statement_T is
skipped and statement_F is executed.
The if...else Selection Statement
■ if
– Only performs an action if the condition is true
■ if…else
– Specifies an action to be performed both when the condition is
true and when it is false
The if...else Selection Statement
■ Compound statement:
– Set of statements within a pair of braces
■ Example:
if ( grade >= 60 )
printf( "Passed.\n" );
else
{
printf( "Failed.\n" );
printf( "You must take this course again.\n" );
}
The if..else Selection Statement
switch ( a_variable ){
case value1:
actions;
break;
case value2 :
actions;
break;
...
default:
actions;
}
Exercise
■ Sequence structures:
– Programs executed sequentially by default
■ Selection structures:
– if, if…else, and switch
■ Repetition structures:
– while, do…while and for
Repetition in Programs
■ loop
– a control structure that repeats a group of steps in a program
■ loop body
– the statements that are repeated in the loop
Repetition in Programs
■ Counter-controlled iteration
– Counter-controlled iteration is sometimes called definite iteration
because we know in advance exactly how many times the loop
will be executed.
■ Sentinel-controlled iteration
– Sentinel-controlled iteration is sometimes called indefinite
iteration because it’s not known in advance how many times the
loop will be executed.
Repetition in Programs
■ the for loop supplies a designated place for each of these three
components
The for Statement Syntax
■ Because the control variable is now equal to 2, the final value is not
exceeded, so the program performs the printf statement again.
■ This process continues until the control variable counter is
incremented to its final value of 11—this causes the loop-continuation
test to fail, and iteration terminates.
■ The program continues by performing the first statement after the for
statement (in this case, the end of the program).
for Iteration Statement
■ Notice that the for statement “does it all”—it specifies each of the
items needed for counter-controlled iteration with a control variable.
■ If there’s more than one statement in the body of the for, braces are
required to define the body of the loop.
for Iteration Statement
Off-By-One Errors
Off-By-One Errors
■ Using the final value in the condition of a while or for statement and
using the <= relational operator can help avoid off-by-one errors. For a
loop used to print the values 1 to 10, for example, the loop
continuation condition should be counter <= 10 rather than
counter < 11 or counter < 10.
for Iteration Statement
■ Sequence structures:
– Programs executed sequentially by default
■ Selection structures:
– if, if…else, and switch
■ Repetition structures:
– while, do…while and for
do…while Iteration Statement
do
{
statement;
}
while (loop repetition condition);
do…while Iteration Statement
■ break
– Causes immediate exit from a while, for, do…while or
switch statement
– Program execution continues with the first statement after
the structure
■ continue
– Skips the remaining statements in the body of a while, for or
do…while statement
– Proceeds with the next iteration of the loop
■ while and do…while
– Loop-continuation test is evaluated immediately after the
continue statement is executed
■ for
– Increment expression is executed, then the loop-continuation
test is evaluated
The break and continue Statements
CEN111
FUNCTIONS I
Introduction
■ We have already written our own functions and used library functions:
– main is a function that must exist in every C program.
– printf, scanf are library functions which we have already used in
our programs.
■ We can write our own functions to define tasks that may be used at
many points in a program.
■ These are sometimes referred to as programmer-defined functions.
Functions
■ Most functions have a list of parameters that provide the means for
communicating information between functions.
■ return;
■ return 1.5;
■ return result;
■ return a+b*c;
■ return x < y ? x : y;
Example
if (IsLeapYear(2005))
printf(“29 days in February.\n”);
else
printf(“28 days in February.\n”);
Example
– In declaration header:
int f (int x, double y, char c);
– In function calling:
value = f(age, score, initial);
Parameters
Output:
5
0
5
15
Function Prototypes
■ Local variables can only be accessed in the function in which they are
defined.
■ If a variable is defined outside any function at the same level as
function definitions, it is available to all the functions defined below in
the same source file
– external variable
■ Global variables: external variables defined before any function
definition
– Their scope will be the whole program
Local
Variables
Output:
5
5
6
5
5
6
Global
Variables
Output:
5
5
6
6
6
7
Static Variables
Output:
6 6 5 5 6
5 1 1 5 3
6 6 2 4 2
6 2 3 4 1
Random Number Generation
■ The recursion step can result in many more such recursive calls, as
the function keeps dividing each problem it’s called with into two
conceptual pieces.
■ For the recursion to terminate, each time the function calls itself with
a slightly simpler version of the original problem, this sequence of
smaller problems must eventually converge on the base case.
■ When the function recognizes the base case, returns a result to the
previous copy of the function, and a sequence of returns ensues all
the way up the line until the original call of the function eventually
returns the final result to main.
Recursion
■ They have the same level of precedence as the function call operator
(i.e., the parentheses that are placed after a function name to call
that function).
Defining Arrays
■ The definition
int b[100], x[27];
reserves 100 elements for integer array b and 27 elements for integer
array x.
■ These arrays have indices in the ranges 0–99 and 0–26, respectively.
■ Arrays may contain other data types.
■ Character strings and their similarity to arrays and the relationship
between pointers and arrays will be discussed in next chapters.
Array Examples
Output:
Element Value
0 0
1 0
2 0
3 0
4 0
Array Examples
Output:
Element Value
0 2
1 4
2 6
3 8
4 10
Array Examples
■ If there are fewer initializers than elements in the array, the remaining
elements are initialized to zero.
■ For example, the elements of the array n could have been initialized to
zero as follows:
int n[10] = {0};
■ This explicitly initializes the first element to zero and initializes the
remaining nine elements to zero because there are fewer initializers
than there are elements in the array.
Array Examples
■ If the array size is omitted from a definition with an initializer list, the
number of elements in the array will be the number of elements in the
initializer list.
■ For example,
int n[ ] = {1, 2, 3, 4, 5};
would create a five-element array initialized with the indicated values
ARRAYS II
Static Local Arrays and Automatic Local
Arrays
■ A static local variable exists for the duration of the program but is
visible only in the function body.
■ We can apply static to a local array definition so the array is not
created and initialized each time the function is called and the array is
not destroyed each time the function is exited in the program.
■ This reduces program execution time, particularly for programs with
frequently called functions that contain large arrays.
Static Local Arrays and Automatic Local
Arrays
■ Function staticArrayInit is called twice.
■ The local static array in the function is initialized to zero before
program startup.
■ The function prints the array, adds 5 to each element and prints the
array again.
■ The second time the function is called, the static array contains the
values stored during the first function call.
First call to each function: Second call to each function:
OUTPUT:
The values of the original array are: 0 1 2 3 4
The values of the modified array are: 0 2 4 6 8
■ If there are not enough initializers for a given row, the remaining
elements of that row are initialized to 0.
■ Thus,
■ int b[2][2] = {{1}, {3, 4}};
would initialize b[0][0] to 1, b[0][1] to 0, b[1][0] to 3 and
b[1][1] to 4.
Multidimensional Arrays