You are on page 1of 280

CEN111

INTRODUCTION
Dr. Barış ATA
CEN111 Algorithms and Programming I

■ Fall 2022-2023

■ Instructor: Dr. Barış ATA (bata@cu.edu.tr)

■ Office Hours: Thursday 13:00-15:00


■ Grading: Midterm 40 %, Final exam 60 %.
Description

■ 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

■ Problem Solving and Program Design in C —7th ed,


– Jeri R. Hanly, Elliot B. Koffman

■ C How to Program, 8th ed,


– Paul Deitel, Harvey Deitel
References

■ C Programming Language -2nd Edition


– Brian W. Kernighan, Dennis M. Ritchie

■ C Programlama Dili
– Rifat Çölkesen

■ C Dersi: Programlamaya Giriş


– Nergiz Ercil Çağıltay,C. Fügen Elbes, Gül Tokdemir, Çiğdem Turhan
Required Software

■ Raptor Flowchart based Programming Environment

■ Microsoft Visual Studio


Computers

■ 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

■ Stored program concept


– a computer’s ability to store program instructions in main memory for
execution
■ Byte
– the amount of storage required to store a single character
■ Bit
– a binary digit, a 0 or a 1
Bit

00101100
Byte
Memory

■ Random access memory (RAM)


– the part of main memory that temporarily stores programs, data, and results

■ Read-only memory (ROM)


– the part of main memory that permanently stores programs or data
Secondary 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

■ Central Processing Unit (CPU)


– coordinates all computer operations and performs arithmetic and logical
operations on data
■ Fetching an instruction
– retrieving an instruction from main memory
■ Register
– high-speed memory location inside the CPU
■ Multiprocessor
– a computer with more than one CPU
Input/Output Devices

■ 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

■ Operating system (OS)


– software that controls interaction of user and computer hardware and that
manages allocation of computer resources
■ Booting a computer
– loading the operating system from disk into memory
Application Software

■ 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

1. Specify the problem requirements.


2. Analyze the problem.
3. Design the algorithm to solve the problem.
4. Implement the algorithm
5. Test and verify the completed program.
6. Maintain and update the program.

22
CEN111
ALGORITHMS
Introduction

■ Problem

■ Problem Solving
Algorithms

■ Problem solving phase


– produce an ordered sequence of steps that describe
solution of problem

■ Implementation phase
– implement the program in some programming language
Algorithms

■ The word is derived from the phonetic pronunciation of the


last name of Abu Ja'far Mohammed ibn Musa al-
Khowarizmi.
■ An algorithm is a sequence of steps to solve a particular
problem
■ An algorithm is an ordered set of unambiguous steps that
produces a result and terminates in a finite time
Algorithms

■ It is a step-by-step representation of a solution to a given


problem
■ An algorithm uses a definite procedure.
■ It is not dependent on any programming language.
■ Every step in an algorithm has its own logical sequence.
Properties of Algorithms

■ Finiteness: An algorithm must always terminate after a finite number of steps.


■ Definiteness: Each step of an algorithm must be precisely defined. Also the actions
are defined unambiguously for each activity in the algorithm.
■ Input: Any operation you perform need some beginning value/quantities associated
with different activities in the operation.
■ Output: One always expects output/result (expected value/quantities) in terms of
output from an algorithm.
■ Effectiveness: Algorithms to be developed/written using basic operations.
Algorithms

■ Define your algorithms input


■ Define the variables
■ Outline the algorithm's operations
■ Output the results of your algorithm's operations
Algorithms

■ Unambiguous
■ Executable
■ Ordered
Algorithms

■ Find the area of a circle of radius r.


Inputs to the algorithm: Radius of the circle.
Expected output: Area of the circle
Algorithm:
1. Start
2. Get radius r
3. area=PI*r*r
4. Print area
5. End
Pseudocode

■ Pseudocode is an artificial and informal language that helps programmers develop


algorithms. Pseudocode is very similar to everyday English.

■ pseudo - code it cannot be executed on a real computer, but it models and


resembles real programming code, and is written at roughly the same level of detail.
Some Keywords

■ Start - End
■ Goto
■ Set, Initialize
■ Read, Get
■ Print, Write, Display
Assignment

■ ← or = is used to assign value to a variable


■ to assign value 3 to the variable radius, the statement is
radius=3 or radius ←3

– C=A+B

– R=R+1
Mathematical Operators

Operator Meaning Example


+ Addition A+B
- Substraction A-B
* Multiplication A*B
/ Divison A/B
^ Power A^B
% Reminder A%B
Algorithms

■ Find the sum of two numbers


var: number1,number2,sum
1. Start
2. Get number1
3. Get number2
4. sum=number1+number2
5. Print sum
6. End
Algorithms

■ Find the avarege of two numbers


var: number1,number2,sum,avg
1. Start
2. Get number1
3. Get number2
4. sum=number1+number2
5. avg=sum/2
6. Print avg
7. End
Structures

■ Sequence
■ Branching (Selection)
■ Loop (Repetition)
Relational Operators

Operator Meaning Example


< Less than A<B
<= Less than or equal to A <=B
== Equal to A == B
!= Not equal to A != B
> Greater than A>B
>= Greater than or equal to A >=B
Algorithms

■ 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

Operator Example Meaning


AND A<B AND B<C Result is true if both
conditions are true else false
OR A<B OR B<C Result is true if either A<B or
B<C are true else false
NOT NOT (A<B) Result is true if A<B is false
else true
Algorithms
■ Find the greatest of three numbers

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.

■ A flowchart is a graphical representation of an algorithm.

■ Once the flowchart is drawn, it becomes easy to write the program in any high level
language.
Flowchart Symbols

■ Terminal

■ Indicates the starting or ending of the process.


Flowchart Symbols

■ Flow lines

■ An arrow coming from one symbol and ending at another symbol.


■ Shows direction of flow.
Flowchart Symbols

■ Process

■ Indicates any type of internal operation inside the processor or memory


Flowchart Symbols

■ Input/output

■ Used for any I/O operation. Indicates that the computer is to obtain data or output
results.

Input Output
Flowchart Symbols

■ Decision

■ Used to ask a question that can be answered in a binary format.


Flowchart Symbols

■ Connector

■ Allows the flowchart to be drawn without intersecting lines or without a reverse flow.
Flowchart Symbols

■ Predefined process

■ Used to invoke asubroutine or an interrupt program..


Flowcharts

■ All boxes of the flowchart are connected with arrows.


■ Flowchart symbols have an entry point on the top of the symbol with no other entry
points. The exit point for all flowchart symbols is on the bottom except for the
Decision symbol.
■ The Decision symbol has two exit points; these can be on the sides or the bottom
and one side.
■ Generally a flowchart will flow from top to bottom. However, an upward flow can be
shown as long as it does not exceed 3 symbols.
Flowcharts

■ Connectors are used to connect breaks in the flowchart.


– From one page to another page.
– From the bottom of the page to the top of the same page.
– An upward flow of more then 3 symbols
■ Subroutines and Interrupt programs have their own and independent flowcharts.
■ All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
■ All flowcharts end with a terminal.
START
Problem
GET
number1

■ Find the sum of two numbers


var: number1,number2,sum GET
number2
1. Start
2. Get number1
sum=number1
3. Get number2 +number2
4. sum=number1+number2
5. Print sum
PRINT sum
6. End

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.

– Once the conditional execution is


finished, the flows rejoin before
leaving the structure.
Basic Control Structures

■ 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

■ Prepare a flowchart to read the marks of a student and classify


them into different grades. If the marks secured are greater than
or equal to 90, the student is awarded Grade A; if they are greater
than or equal to 80 but less than 90, Grade B is awarded; if they
are greater than or equal to 65 but less than 80, Grade C is
awarded; otherwise Grade D is awarded.
Algorithms

■ Draw a flowchart to find the sum of the first 50 natural numbers.


Algorithms

■ Develop the algorithm for finding the sum of the series 1 + 2 + 3 +


4 + … up to N.
Algorithms

■ Develop the algorithm for finding the sum of the series 2 + 4 + 8 +


… up to N.
Homework

■ Draw a flowchart to find the roots of a quadratic equation.

■ Draw a flowchart to find the greatest common divisor of two given


number.
CEN111

OVERVIEW OF C
History of C

■ C is a high-level programming language developed by Denis


Ritchie at AT&T Bell Labs in 1972
■ Used to write modern operating systems
■ Combines some important qualities of high and low level
languages
■ Allows programmers to develop application software as well
as system software
Phases of C Programs

1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
The Programming Process

edit program compile execute

■ The cycle ends once the programmer is satisfied with the


performance of the program
A Simple C Program

/* Hello World Example */


#include <stdio.h>
int main (void)
{
printf(“Hello world!\n”);
return 0;
}
Comments

/* Hello World Example */

■ /* and */ indicates that is a comment


■ Text surrounded by /* and */ is ignored by compiler
■ Used to describe program
■ Comment Line: // compiler ignores everything from there
until the end of the line
Preprocessor Directives

#include <stdio.h>

■ The preprocessor directives are commands that give


instructions to the C preprocessor, whose job it is to modify
the text of a C program before its compiled.
■ A preprocessor directive begins with a number symbol (#) as
its first nonblank character.
Preprocessor Directives

#include <stdio.h>

■ The #include directive gives a program access to a certain


library
■ #include <stdio.h> notifies the preprocessor that some
names used in the program are found in the standard
header file <stdio.h>.
#include Directive

■ SYNTAX:
#include <standard header file>
■ EXAMPLES:
#include <stdio.h>
#include <math.h>
Function main

int main (void)

■ C programs contain one or more functions, exactly one of


which must be main
■ int means that main "returns" an integer value
■ void indicates that the function takes no arguments
■ Braces, { and } indicate a block. The bodies of all functions
must be contained in braces
main Function Definition

■ SYNTAX:

int main(void)
{
function body
}
The printf Function

printf(“Hello world!\n”);

■ The printf function displays the value of its format string


■ Entire line called a statement. All statements must end with
a semicolon (;)
■ Escape character (\) Indicates that printf should do
something out of the ordinary
■ \n is the newline character
The return Statement

return 0;

■ Last line in the main function.


■ Transfers control from your program to the operating system.
■ The value 0 ,in this case, indicates that your program
executed without an error.
■ Right brace } indicates end of main has been reached
Language Elements

■ Token: the smallest element of a program that is meaningful


to the compiler.
■ Kinds of tokens in C:
– Reserved words
– Identifiers
– Constants
– Operators
– Punctuators
Reserved Words

■ a word that has a special meaning in C


■ identifiers from standard library and names for memory cells
■ appear in lowercase
■ cannot be used for other purposes
Reserved Words

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers

■ Identifiers are used for:


– Variable names
– Function names
– Macro names
Identifiers

■ An identifier must consist only of letters, digits, and


underscores.
■ An identifier cannot begin with a digit.
■ A C reserved word cannot be used as an identifier.
■ An identifier defined in a C standard library should not be
redefined.
■ Case-sensitive e.g. Ali and ali are two different identifiers.
Identifiers

■ 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

A declaration consists of a data type name followed by a list of


(one or more) variables of that type:
– char c;
– int num1, num2;
– float rate;
– double avarage;
Variable Declarations

A variable may be initialized in its declaration.


– char c = ‘a’;
– int a = 220, b = 448;
– float x = 0.00123
– double y = 123.00
Variable Declarations

■ Variables that are not initialized may have garbage values.


■ Whenever a new value is placed into a variable, it replaces
the previous value
■ Reading variables from memory does not change them
Simple Macros
■ C provides a #define directive to define symbolic names for constants:

#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

■ variable = expression; x = 5*y + (y-1)*44 ;


■ expressions:
expression
– operations
– variables statement
– constants
– function calls
■ Precedence of the assignment operator is lower than the
arithmetic operators
Assignment Operator

■ an instruction that stores a value of a computational result in


a variable

■ x=y ; l-value vs. r-value


■ x+1 = 3; invalid l-value expression
■ l-value usages must refer to a fixed position in the memory
Increment and Decrement Operators

■ 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;

■ operand1=operand1 operator operand2


■ operand1 operator=operand2
Integer/Float Conversions
■ An arithmetic operation between an integer and an integer
always yields an integer result .
■ An arithmetic operation between a float and a float always
yields a float result.
■ In an arithmetic operation between an integer and a float, the
integer is first promoted to float and then the operation is
carried out. Hence, it always yields a float result.
■ On assigning a float to an integer, the float is demoted to an
integer
■ On assigning an integer to a float, it is promoted to a float.
Input and Output

■ 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

■ The printf Function displays a line of program output.


■ function argument
– enclosed in parentheses following the function name
– provides information needed by the function
■ format string
– in a call to printf, a string of characters enclosed in quotes, which
specifies the form of the output line
■ printf(“<format string> “, <list of variables>)
The printf Function
■ print list
– in a call to printf, the variables or expressions whose values are
displayed
■ placeholder
– a symbol beginning with % in a format string that indicates where
to display the output value

printf(“That equals %f kilometers. \n”, kms);


The printf Function

■ Placeholders in format string


– %c: the argument is taken to be a single character
– %d: the argument is taken to be an integer
– %f: the argument is taken to be a floating point (float or
double)
– %s: the argument is taken to be a string
The scanf Function

■ Copies data from the standard input device (usually the


keyboard) into a variable.

■ scanf(“<format string“>, <address of variables>)

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

■ Write a C program to convert entered fahrenheit degree to


celsius degree.
Homework

■ Write a C program to reverse a given 5 digits number.


CEN111
SELECTION STRUCTURES
Structures

■ 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

■ selection control structure


– a control structure that chooses among alternative program statements

?
Conditions

■ an expression that is either false


– represented by 0
■ or true
– usually represented by 1

rest_heart_rate > 75
Relational and Equality Operators

Operator Meaning Type


< less than relational
> greater than relational
<= less than or equal to relational
>= greater than or equal to relational
== equal to equality
!= not equal to equality
Relational Operators

■ The relational operators are <, >, <=, and >=.


■ Take 2 expressions as operands
■ Yield either the int value 0 (false) or the int value 1 (true).

Example: assume a = 1, b=2.


Expression Value
a <= b 1
a < b-5 0
a + 10 / b <= -3 + 8 0
Equality Operators

■ The equality operators are == and !=.


■ Yield either the int value 0 or the int value 1.

Examples: assume a=1, b=2, ch = ‘A’


Expression Value
a == b 0
a != b 1
ch < ‘B’ 1
a+b == -2 * 3 0
Equality Operators

■ Note carefully that the two expressions a == b and a = b are visually


similar.

■ 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

■ Expressions connected by && or || are evaluated left to right.


■ logical complement (negation):!
– the complement of a condition had the value 1 (true) when the
condition’s value is 0 (false)
– the complement of a condition has the value 0 (false) when the
condition’s value is nonzero (true)
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;

INTERPRETATION: If condition evaluates to true (a nonzero value), then


statement_T is executed; otherwise, statement_T is skipped.
The if...else Selection Statement

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

■ Ternary conditional operator (?:)


– Takes three arguments (condition, value if true, value if false)

grade >= 60 ? printf( “Passed\n” ) : printf( “Failed\n”);


Nested if/else structures

■ Test for multiple cases by placing if…else selection statements inside


if…else selection statement
■ Once condition is met, rest of statements skipped
■ Deep indentation usually not used in practice
Nested if/else structures
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
Nested if/else structures
if (expr1)
statement1
else if(expr2)
statement2
else if(expr3)
statement3
……
else if(exprN)
statementN
else
default statement
next statement
Nested if/else structures

if(grade >= 90)


printf(“A”);
else if (grade >= 80)
printf(“B”);
else if (grade >= 70)
printf(“C”);
else if (grade >= 60)
printf(“D”);
else
printf(“F”);
The switch Multiple-Selection Structure

■ used to select one of several alternatives


■ useful when the selection is based on the value of
– a single variable
– or a simple expression
■ values may of type int or char
– not double
The switch Multiple-Selection Structure

switch ( a_variable ){
case value1:
actions;
break;
case value2 :
actions;
break;
...
default:
actions;
}
Exercise

■ Write a simple calculator using the switch multiple-selection structure


CEN111
REPETITION STRUCTURES I
Structures

■ 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

■ In counter-controlled iteration, a control variable is used to count the


number of iterations.
■ The control variable is incremented (usually by 1) each time the group
of instructions is performed.
■ When the value of the control variable indicates that the correct
number of iterations has been performed, the loop terminates and
execution continues with the statement after the iteration statement.
Repetition in Programs

■ Sentinel values are used to control iteration when:


– The precise number of iterations isn’t known in advance, and
– The loop includes statements that obtain data each time the loop
is performed.
■ The sentinel value indicates “end of data.”
■ The sentinel is entered after all regular data items have been supplied
to the program.
■ Sentinels must be distinct from regular data items.
Counting Loops

■ Counter-controlled iteration requires:


– The name of a control variable (or loop counter).
– The initial value of the control variable.
– The increment (or decrement) by which the control variable is
modified each time through the loop.
– The condition that tests for the final value of the control variable
(i.e., whether looping should continue).
while Statement Syntax

while (loop repetition condition)


{
statement;
}
while Statement Syntax
General Conditional Loop

1. Initialize loop control variable.


2. As long as exit condition hasn’t been met
3.Continue processing
Loop Control Components

■ initialization of the loop control variable


■ test of the loop repetition condition
■ change (update) of the loop control variable

■ the for loop supplies a designated place for each of these three
components
The for Statement Syntax

for (initialization expression; loop repetition condition; update expression)


statement;
for Iteration Statement

■ When the for statement begins executing, the control variable


counter is initialized to 1.
■ Then, the loop-continuation condition counter <= 10 is checked.
■ Because the initial value of counter is 1, the condition is satisfied, so
the printf statement prints the value of counter, namely 1.
■ The control variable counter is then incremented by the expression
counter++, and the loop begins again with the loop-continuation
test.
for Iteration Statement

■ 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

■ Notice that the loop-continuation condition counter <= 10.


■ If you incorrectly wrote counter < 10, then the loop would be executed
only 9 times.
■ This is a common logic error called an off-by-one error.
for Iteration Statement

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

Comma-Separated Lists of Expressions

■ Often, the initialization and increment expressions are comma-


separated lists of expressions.
■ The commas as used here are actually comma operators that
guarantee that lists of expressions evaluate from left to right.
for Iteration Statement

■ The comma operator is most often used in the for statement.


■ Its primary use is to enable you to use multiple initialization and/or
multiple increment expressions.
■ For example, there may be two control variables in a single for
statement that must be initialized and incremented.
for Iteration Statement

Expressions in the for Statement’s Header Are Optional


■ The three expressions in the for statement are optional.
■ If the condition expression is omitted, C assumes that the condition is
true, thus creating an infinite loop.
■ You may omit the initialization expression if the control variable is
initialized elsewhere in the program.
■ The increment may be omitted if it’s calculated by statements in the
body of the for statement or if no increment is needed.
for Iteration Statement

Increment Expression Acts Like a Standalone Statement


■ The increment expression in the for statement acts like a stand-alone C statement at the
end of the body of the for.
■ Therefore, the expressions
counter = counter + 1
counter += 1
++counter
counter++
are all equivalent in the increment part of the for statement.
■ Because the variable being preincremented or postincremented here does not appear in
a larger expression, both forms of incrementing have the same effect.
■ The two semicolons in the for statement are required.
for Iteration Statement

■ The initialization, loop-continuation condition and increment can contain


arithmetic expressions. For example, if x = 2 and y = 10, the statement
for (j = x; j <= 4 * x * y; j += y / x)
is equivalent to the statement
for (j = 2; j <= 80; j += 5)
■ The “increment” may be negative (in which case it’s really a decrement and
the loop actually counts downward).
■ If the loop-continuation condition is initially false, the loop body does not
execute. Instead, execution proceeds with the statement following the for
statement.
Examples Using the for Statement
■ The following examples show methods of varying the control variable in a for
statement.

– Vary the control variable from 1 to 100 in increments of 1.


for (i = 1; i <= 100; i++ )
– Vary the control variable from 100 to 1 in increments of -1 (decrements of 1).
for (i = 100; i >= 1; i--)
– Vary the control variable from 7 to 77 in steps of 7.
for (i = 7; i <= 77; i += 7)
– Vary the control variable from 20 to 2 in steps of -2.
for (i = 20; i >= 2; i -= 2)
– Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17.
for (j = 2; j <= 17; j += 3)
– Vary the control variable over the following sequence of values: 44, 33, 22, 11, 0.
for (j = 44; j >= 0; j -= 11)
Examples Using the for Statement

■ Application: Summing the Even Integers from 2 to 100


Homework

■ Write a C program to find the factorial of an integer entered by user.


■ Write a C program to count number of digits in an integer entered by
user.
CEN111
REPETITION STRUCTURES II
Structures

■ 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

■ The do…while iteration statement is similar to the while statement.


■ In the while statement, the loop-continuation condition is tested at
the beginning of the loop before the body of the loop is performed.
■ The do…while statement tests the loop-continuation condition after
the loop body is performed.
■ Therefore, the loop body will be executed at least once.
■ When a do…while terminates, execution continues with the
statement after the while clause.
do…while Iteration Statement
Nested Loops

■ When a loop body includes another loop construct


this is called a nested loop.

■ In a nested loop structure the inner loop is executed


from the beginning every time the body of the outer
loop is executed.
Nested Loops

■ How many times the inner loop is executed?


Nested Loops
The break and continue Statements

■ break
– Causes immediate exit from a while, for, do…while or
switch statement
– Program execution continues with the first statement after
the structure

■ Common uses of the break statement


– Escape early from a loop
– Skip the remainder of a switch statement
The break and continue Statements
The break and continue Statements

■ 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

■ Most computer programs that solve real-world problems are much


larger than the programs presented in the first few chapters.
■ Experience has shown that the best way to develop and maintain a
large program is to construct it from smaller pieces, each of which is
more manageable than the original program.
■ This technique is called divide and conquer.
Introduction

■ Functions are used to modularize programs


■ C programs are typically written by combining new functions you write
with prepackaged functions available in the C standard library.
■ The C standard library provides a rich collection of functions for
performing common mathematical calculations, string manipulations,
character manipulations, input/output, and many other useful
operations.
Functions

■ 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

■ We need to do two things with functions:


– Create functions
– Call functions (Function invocation)

■ Functions are invoked by a function call, which specifies the function


name and provides information (as arguments) that the called
function needs to perform its designated task.
Function Definiton

A function definition has the following form:

return_type function_name (parameter-declarations)


{
variable-declarations;
function-statements;
}
Function Definiton

■ return_type - specifies the type of the function and corresponds to the


type of value returned by the function
– void – indicates that the function returns nothing.
– if not specified, of type int
■ function_name – name of the function being defined (any valid
identifier)
■ parameter-declarations – specify the types and names of the
parameters (a.k.a. formal parameters) of the function, separated by
commas.
Function Definiton

■ return_type - specifies the type of the function and corresponds to the


type of value returned by the function
– void – indicates that the function returns nothing.
– if not specified, of type int
■ function_name – name of the function being defined (any valid
identifier)
■ parameter-declarations – specify the types and names of the
parameters (a.k.a. formal parameters) of the function, separated by
commas.
Example: Function returning a value

This function can be called as:


n = cube(5);
Example: void Function

This function can be called as:


message( );
Functions

■ All variables defined in function definitions are local variables—they


can be accessed only in the function in which they’re defined.

■ Most functions have a list of parameters that provide the means for
communicating information between functions.

■ A function’s parameters are also local variables of that function.


The return statement

■ When a return statement is executed, the execution of the function is


terminated and the program control is immediately passed back to the
calling environment.
■ If an expression follows the keyword return, the value of the
expression is returned to the calling environment as well.
■ A return statement can be one of the following two forms:
– return;
– return expression;
The return statement

■ return;
■ return 1.5;
■ return result;
■ return a+b*c;
■ return x < y ? x : y;
Example

This function may be called as:

if (IsLeapYear(2005))
printf(“29 days in February.\n”);
else
printf(“28 days in February.\n”);
Example

Input two integers: 5 6


The minimum is 5.

Input two integers: 11 3


The mininum is 3.
Parameters

■ A function can have zero or more parameters.

– In declaration header:
int f (int x, double y, char c);

– In function calling:
value = f(age, score, initial);
Parameters

■ The number of parameters in the actual and formal parameter lists


must be consistent
■ Parameter association is positional: the first actual parameter
matches the first formal parameter, the second matches the second,
and so on
■ Actual parameters and formal parameters must be of compatible data
types
■ Actual parameters may be a variable, constant, any expression
matching the type of the corresponding formal parameter
Parameters

■ Each argument is evaluated, and its value is used locally in place of


the corresponding formal parameter.
■ If a variable is passed to a function, the stored value of that variable in
the calling environment will not be changed.
■ In C, all calls are call-by-value unless specified otherwise.
Parameters

Output:
5
0
5
15
Function Prototypes

■ General form for a function prototype declaration:


– return_type function_name (parameter-type-list);
■ Used to validate functions
– Prototype only needed if function definition comes after use in
program
■ The function with the prototype
int maximum( int, int, int );
Takes in 3 ints
Returns an int
Alternative
styles for
function
definition order
Alternative
styles for
function
definition order
FUNCTIONS II
External Variables

■ 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

■ A variable is said to be static if it is allocated storage at the beginning


of the program execution and the storage remains allocated until the
program execution terminates.
■ External variables are always static
■ Within a block, a variable can be specified to be static by using the
keyword static before its type declaration:
– static type variable-name;
■ Variable declared static can be initialized only with constant
expressions (if not, its default value is zero)
Static
Variables
Output:
5
5
6
5
6
7
Math Library Functions

■ Math library functions


– perform common mathematical calculations
– #include <math.h>
floor of 5.10 is 5.000000
floor of 5.90 is 5.000000
floor of -5.40 is -6.000000
floor of -6.90 is -7.000000
ceil of 5.10 is 6.000000
ceil of 5.90 is 6.000000
ceil of -5.40 is -5.000000
ceil of -6.90 is -6.000000
Random Number Generation

■ The element of chance can be introduced into computer applications


by using the C standard library function rand from the <stdlib.h>
header.
■ Consider the following statement:
– i = rand();
■ The rand function generates an integer between 0 and RAND_MAX (a
symbolic constant defined in the <stdlib.h> header).
Random Number Generation

■ Standard C states that the value of RAND_MAX must be at least


32767, which is the maximum value for a two-byte (i.e., 16-bit) integer.
■ If rand truly produces integers at random, every number between 0
and RAND_MAX has an equal chance (or probability) of being chosen
each time rand is called.
■ The range of values produced directly by rand is often different from
what’s needed in a specific application.
Random Number Generation

■ For example, a dice-rolling program that simulates a six-sided dice


would require random integers from 1 to 6
■ We use the remainder operator (%) in conjunction with rand as follows
rand() % 6
to produce integers in the range 0 to 5.

▪ This is called scaling.


Random Number Generation

■ The number 6 is called the scaling factor.

■ We then shift the range of numbers produced by adding 1 to our


previous result
1+rand() % 6
Random Number Generation

Output:

6 6 5 5 6
5 1 1 5 3
6 6 2 4 2
6 2 3 4 1
Random Number Generation

■ Executing that program again produces exactly the same sequence of


values.
■ How can these be random numbers? Ironically, this repeatability is an
important characteristic of function rand.
■ Function rand actually generates pseudorandom numbers.
■ Calling rand repeatedly produces a sequence of numbers that
appears to be random.
■ However, the sequence repeats itself each time the program is
executed.
Random Number Generation

■ Once a program has been thoroughly debugged, it can be conditioned


to produce a different sequence of random numbers for each
execution.
■ This is called randomizing and is accomplished with the standard
library function srand.
■ Function srand takes an unsigned integer argument and seeds
function rand to produce a different sequence of random numbers for
each execution of the program.
Random Number Generation
Random Number Generation
Random Number Generation

■ To randomize without entering a seed each time, use a statement like


srand(time(NULL));
■ This causes the computer to read its clock to obtain the value for the
seed automatically.
■ Function time returns the number of seconds that have passed since
midnight on January 1, 1970.
■ This value is converted to an unsigned integer and used as the seed
to the random number generator.
■ The function prototype for time is in <time.h>.
Random Number Generation
Recursion

■ The programs we’ve discussed are generally structured as functions


that call one another in a disciplined, hierarchical manner.
■ For some types of problems, it’s useful to have functions call
themselves.
■ A recursive function is a function that calls itself either directly or
indirectly through another function.
■ Recursion is a complex topic discussed at length in upper-level
computer science courses.
■ In this section and the next, simple examples of recursion are
presented.
Recursion

■ Recursive problem-solving approaches have a number of elements in


common.
■ A recursive function is called to solve a problem.
■ The function actually knows how to solve only the simplest case(s), or
so-called base case(s).
■ If the function is called with a base case, the function simply returns a
result.
■ If the function is called with a more complex problem, the function
divides the problem into two conceptual pieces: a piece that the
function knows how to do and a piece that it does not know how to do.
Recursion

■ To make recursion feasible, the latter piece must resemble the


original problem, but be a slightly simpler or smaller version.
■ Because this new problem looks like the original problem, the function
launches (calls) a fresh copy of itself to go to work on the smaller
problem—this is referred to as a recursive call or the recursion step.
■ The recursion step also includes the keyword return, because its
result will be combined with the portion of the problem the function
knew how to solve to form a result that will be passed back to the
original caller.
■ The recursion step executes while the original call to the function is
paused, waiting for the result from the recursion step.
Recursion

■ 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

Recursively Calculating Factorials


■ The factorial of a nonnegative integer n, written n! (pronounced “n factorial”),
is the product
n · (n –1) · (n – 2) · … · 1
with 1! equal to 1, and 0! defined to be 1.
■ A recursive definition of the factorial function is arrived at by observing the
following relationship:
n! = n · (n – 1)!
■ For example, 5! is clearly equal to 5 * 4! as is shown by the following:
5! = 5 · 4 · 3 · 2 · 1
5! = 5 · (4 · 3 · 2 · 1)
5! = 5 · (4!)
Recursion
Output:
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
10!=3628800
ARRAYS I
Arrays

■ Arrays are data structures consisting of related data items of the


same type.
■ An array is a group of contiguous memory locations that all have the
same type.
■ To refer to a particular location or element in the array, we specify the
array’s name and the position number of the particular element in the
array.
Arrays

■ This figure shows an integer


array called c, containing 12
elements.
Arrays

■ Any one of these elements may be referred to by giving the array’s


name followed by the position number of the particular element in
square brackets ([ ]).
■ The first element in every array is the zeroth element.
■ An array name, like other identifiers, can contain only letters, digits
and underscores and cannot begin with a digit.
■ The position number within square brackets is called an index or
subscript.
■ An index must be an integer or an integer expression.
Arrays

■ Any one of these elements may be referred to by giving the array’s


name followed by the position number of the particular element in
square brackets ([ ]).
■ The first element in every array is the zeroth element.
■ An array name, like other identifiers, can contain only letters, digits
and underscores and cannot begin with a digit.
■ The position number within square brackets is called an index or
subscript.
■ An index must be an integer or an integer expression.
Arrays

■ For example, if a = 5 and b = 6, then the statement


c[a + b] += 2;
adds 2 to array element c[11].

■ An indexed array name is an lvalue—it can be used on the left side of


an assignment
Arrays

■ Let’s examine array c more closely.


■ The array’s name is c.
■ Its 12 elements are referred to as c[0], c[1], c[2], …, c[10] and c[11].
■ The value stored in c[0] is –45, the value of c[1] is 6, c[2] is 0, c[7] is
62 and c[11] is 78.
■ To print the sum of the values contained in the first three elements of
array c, we’d write
printf("%d", c[0] + c[1] + c[2]);
Arrays

■ The brackets used to enclose the index of an array are actually


considered to be an operator in C.

■ 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

■ Arrays occupy space in memory.


■ You specify the type of each element and the number of elements
each array requires so that the computer may reserve the appropriate
amount of memory.
■ The following definition reserves 12 elements for integer array c,
which has indices in the range 0-11.
int c[12];
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

■ The elements of an array can also be initialized when the array is


defined by following the definition with an equals sign and braces, {},
containing a comma-separated list of array initializers.
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

■ It’s important to remember that arrays are not automatically initialized


to zero.
■ You must at least initialize the first element to zero for the remaining
elements to be automatically zeroed.
■ The array definition
int n[5] = {32, 27, 64, 18, 95, 14};
causes a syntax error because there are six initializers and only five
array elements.
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:

Values on entering staticArrayInit: Values on entering staticArrayInit:

array1[0]=0 array1[1]=0 array1[2]=0 array1[0]=5 array1[1]=5 array1[2]=5

Values on exiting staticArrayInit: Values on exiting staticArrayInit:

array1[0]=5 array1[1]=5 array1[2]=5 array1[0]=10 array1[1]=10 array1[2]=10

Values on entering automaticArrayInit: Values on entering automaticArrayInit:

array2[0]=1 array2[1]=2 array2[2]=3 array2[0]=1 array2[1]=2 array2[2]=3

Values on exiting automaticArrayInit: Values on exiting automaticArrayInit:

array2[0]=6 array2[1]=7 array2[2]=8 array2[0]=6 array2[1]=7 array2[2]=8


Static Local Arrays and Automatic Local
Arrays
■ Arrays that are static are initialized once at program startup.
■ If you do not explicitly initialize a static array, that array’s elements are
initialized to zero by default.
■ Next demonstrates function staticArrayInit with a local static array and
function automaticArrayInit with a local automatic array.
Static Local Arrays and Automatic Local
Arrays
■ Function automaticArrayInit is also called twice.
■ The elements of the automatic local array in the function are
initialized with the values 1, 2 and 3.
■ The function prints the array, adds 5 to each element and prints the
array again.
■ The second time the function is called, the array elements are
initialized to 1, 2 and 3 again because the array has automatic
storage duration.
Passing Arrays to Functions

■ To pass an array argument to a function, specify the array’s name


without any brackets.
■ For example, if array hourlyTemperatures has been defined as
int hourlyTemperatures[24];
the function call
modifyArray(hourlyTemperatures, 24);
passes array hourlyTemperatures and its size to function modifyArray.
Passing Arrays to Functions

■ C automatically passes arrays to functions by reference — the called


functions can modify the element values in the callers’ original arrays.
■ The name of the array evaluates to the address of the first element of
the array.
■ Because the starting address of the array is passed, the called
function knows precisely where the array is stored.
■ Therefore, when the called function modifies array elements in its
function body, it’s modifying the actual elements of the array in their
original memory locations.
Passing Arrays to Functions

■ Although entire arrays are passed by reference, individual array


elements are passed by value exactly as simple variables are.
■ To pass an element of an array to a function, use the indexed name of
the array element as an argument in the function call.
Passing Arrays to Functions

■ For a function to receive an array through a function call, the


function’s parameter list must specify that an array will be received.
■ For example, the function header for function modifyArray might be
written as
void modifyArray(int b[ ], int size)
indicating that modifyArray expects to receive an array of integers in
parameter b and the number of array elements in parameter size.
■ The size of the array is not required between the array brackets.
Passing Arrays to Functions

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

The value of a[3] is 6


Value in modifyElement is 12
The value of a[3] is 6
Multidimensional Arrays

▪ Arrays in C can have multiple indices.


▪ A common use of multidimensional arrays is to represent tables of
values consisting of information arranged in rows and columns.
▪ To identify a particular table element, we must specify two indices:
The first (by convention) identifies the element’s row and the second
(by convention) identifies the element’s column.
▪ Multidimensional arrays can have more than two indices.
▪ Tables or arrays that require two indices to identify a particular
element are called two-dimensional arrays.
Multidimensional Arrays
Multidimensional Arrays

▪ Figure illustrates a two-dimensional array, a.


▪ The array contains three rows and four columns, so it’s said to be a 3-
by-4 array.
▪ In general, an array with m rows and n columns is called an m-by-n
array
Multidimensional Arrays

▪ Every element in array a is identified in Figure by an element name of


the form a[ i ][ j ]; a is the name of the array, and i and j are the
indices that uniquely identify each element in a.
▪ The names of the elements in row 0 all have a first index of 0; the
names of the elements in column 3 all have a second index of 3.
Multidimensional Arrays

■ A multidimensional array can be initialized when it’s defined, much


like a one-dimensional array.
■ For example, a two-dimensional array int b[2][2] could be defined
and initialized with
int b[2][2] = {{1, 2}, {3, 4}};
■ The values are grouped by row in braces.
■ The values in the first set of braces initialize row 0 and the values in
the second set of braces initialize row 1.
■ So, the values 1 and 2 initialize elements b[0][0] and b[0][1],
respectively, and the values 3 and 4 initialize elements b[1][0] and
b[1][1], respectively.
Multidimensional Arrays

■ 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

Values in array1 by row are:


123
456
Values in array2 by row are:
123
450
Values in array3 by row are:
120
400

You might also like