lecture 14-16 - sharif university of...
TRANSCRIPT
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 2
Introduction
• Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 3
IntroductionAlgorithms usually work on large data sets Sort a set of numbers
Search a specific number in a set of numbers
How to read and store a set of data?
To read Repeat the scanf statement
Use the loop statements
To store the data Save each data in a single variable??
3000 int variables! ! ! !
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 4
ArrayAn ordered collection of same type variables
A vector of
Integers, chars, floats, …
Example
An array of 8 integer
An array of 5 chars
20 1 3 4 5 6 7
3 1 5 11 10 19 012
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 5
ArrayArrays and structures are “static” entities in
that they remain the same size throughout
program execution.
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 6
Arrays in CArray declaration in C
<Elements’ Type> <identifier>[<size>]
<Elements’ Type>: int, char, float, …
<size>
Old compilers (standard): it should be constant
New compilers (standard): it can be variable
Elements in array
From 0 to (size – 1)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 7
ArrayAn array is a group of memory locations related by the fact that they all have the same name and the same type.
To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array.
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 8
Exampleint num[20];
num is array of 20 integers
num[0] is the first integer variable
num[19] is the last integer
float farr[100];
farr is array of 100 floats
farr[0] is the first float
farr[49] is the 50th float
farr[99] is the last float
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 9 9
One-Dimensional Arrays
• Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100;
• An array is an indexed data structure to represent several variables having the same data type: int y[100];
y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 10 10
One-Dimensional Arrays (cont’d)
• An element of an array is accessed using the array name and an index or subscript,
for example: y[5] which can be used like a variable
• In C, the subscripts always start with 0 and increment by 1, so y[5] is the sixth element
• The name of the array is the address of the first element
y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 11
Example
int number[10];
int i, j = 3;
i = 5; //-1 < i < 10
number[i] = 0;
number[i + j] = 1;
j = number[i];
j = number[i + 1];
j = number[i] + 1;
//6th number is 0
//??
//?
//?
//?
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 12
Array• Generic declaration:
typename variablename[size];– typename is type– variablename is any legal variable name– For example : int a[10];– Defines an array of ints with subscripts ranging from 0 to 9– There are 10*sizeof(int) bytes of memory reserved for this array.
– You can use a[0]=10; x=a[2]; a[3]=a[2]; etc.– You can use scanf("%d",&a[3]);
9876543210
10a
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 13
Array Representationint A[3];
A[2]0x1008
A[1]0x1004
A[0]0x1000
A[-1]
All elements of same type – homogenous
First element (index 0)
Last element (index size - 1)
array[0] = 3;
array[2] = 4;
array[10] = 5;
array[-1] = 6;
sizeof(A)?
sizeof(A[0]) = sizeof(A[1]) = sizeof(A[2])?
No bounds checking!
3 * 4 = 12
4
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 14
Array-Bounds Checking• C, unlike many languages, does NOT check
array bounds subscripts during:
– Compilation (some C compilers will check literals)
– Runtime (bounds are never checked)
• It is the programmer’s responsibility to ensurethat their programs are correctly written anddebugged!
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 15
No Index Out of bound Checking:
There is no index out of bound checking in C, for example the followingprogram compiles fine but may produce unexpected output whenrun.
int main(){
int arr[2];
printf("%d ", arr[3]);printf("%d ", arr[-2]);
return 0;}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 16
Using Constants to Define Arrays
• It is useful to define arrays using constants:
#define MONTHS 12
float a [MONTHS];
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 19
Initializing Arrays• Initialization of arrays can be done by a comma
separated list following its definition• For example:
int array [4] = { 100, 200, 300, 400 };
– This is equivalent to:int array [4];array[0] = 100;array[1] = 200;array[2] = 300;array[3] = 400;
• You can also let the compiler figure out the array sizefor you:
int array[] = { 100, 200, 300, 400};
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 20
Array InitializationWhen the size if known in compile time
If defined as a local variable (automatic storage class) It is not initialized to any value
i = arr[6]; // i = ?
void func(void){
int arr[50];
int
}
If defined as a global variable (external storage class) All elements are initialized to 0int arr[50];
void func(void){
int i = arr[6]; // i = 0
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 21
Array Initialization (cont’d)int num[3]={10, 20, 60};
num is the array of 3 integers, num[0] is 10, …
int num[]={40, 50, 60, 70, 70, 80};
num is the array of 6 integers
int num[10]={40, 50, 60};
num is the array of 10 integers
num[0] is 40, num[1] is 50, num[2] is 60
num[3], num[4], ..., num[9]are 0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 22
Array Initialization (cont’d)70};
Compile
int num[2]={40, 50, 60,
/* warning */
3, [4] = 6};int num[5]={[0] =
/* num[5] = {3, 0, 0, 0, 6} */
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 23
Array Initialization (cont’d)• this will initialize all
elements to 0:
int myArray[10] = { 0 };
// all elements 0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 26
Array Initialization (cont’d)• Remember that objects with static
storage duration will initialize to
0 if no initializer is specified:
• static int myArray[10];
// all elements 0
Array Examples (Cont.)
• Also, In C, it is not compiler error to initialize an array with more elements than specified size.
• For example the below program compiles fine.
int main()
{
// Array declaration by initializing it with more
// elements than specified size.
int arr[2] = {10, 20, 30, 40, 50};
return 0;
}
28
Assigning values to an array
For loops are often used to assign values to an array
Example:
int list[5], i;
for(i=0; i<5; i++){
list[i] = i;
} list[0]
list[3]
list[4]
list[1]
list[2]
0
1
23
4
list[0]
list[1]
list[2]
list[3]
list[4]
OR
for(i=0; i<=4; i++){
list[i] = i;
}
29
Assigning values to an array
Give a for loop to assign the below values to list
int list[5], i;
for(i=0; i<5; i++){
list[i] = 4-i;
}
list[0]
list[3]
list[4]
list[1]
list[2]
4
3
21
0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 30
Accessing Array ElementsArray elements are accessed by using an integer index. Array index starts with0 and goes till size of array minus 1.
int main(){int arr[5];arr[0] = 5;arr[2] = -10;arr[3/2] = 2; // this is same as arr[1] = 2arr[3] = arr[0];
printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]); // 5 2 -10 5
return 0;}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 31
Array Elements• An Example to show that array elements are stored
at contiguous locations
int main(){// an array of 5 integers. If arr[0] is stored at address x,then arr[1] is// stored at x + sizeof(int), arr[2] is stored at x + sizeof(int) + sizeof(int) and so on.
int arr[5], i;printf("Size of integer in this compiler is %u\n", sizeof(int));
for (i=0; i<5; i++)// The use of '&' before a variable name, yields address of variable.printf("Address arr[%d] is %u\n", i, &arr[i]);
return 0;}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 32 32
Find Maximum• Find maximum value in data array
int data[100], max, i;
for (i=0; i<100; i++)
data[i] = (rand() % 100) + 10;
max = data[0];
for (i=1; i<100; i++){
if (data[i] > max)
max = data[i];
}
printf("Max = %d\n",max);
33
Find average
Find average of values in data array
int data[100], sum, i, avg;
for (i=0; i<100; i++)
data[i] =(rand() % 100) + 10;
sum = 0;
for (i=0; i<100; i++){
sum = sum + data[i];
}
avg = (double)sum/100;
printf(“Avg = %lf\n", avg);
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 34 34
Number of elements greater than average
• After finding the average as shown in previous slide, use the following code
count = 0;
for (i=0; i<100; i++){
if (data[i] > avg)
count++;
}
printf(“%d elements are “
“greater than avg”, count);
35
Find pair sum
Find sum of every pair in data and write into pair array
data[0]=5
data[1]=7
data[2]=15
data[3]=5
…
…
data[98]=3
data[99]=12
pair[0]=12
pair[1]=20
…
pair[49]=15
}
}
}
.
.
.
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 36 36
solution
int data[100], pair[50], i;
for (i=0; i<100; i++)
data[i] = (rand() % 100) + 10;
for (i=0; i<50; i++){
pair[i]= data[2*i] + data[2*i+1];
}
37
Randomly re-shuffle numbers 30 times
data[0]=5
data[1]=7
data[2]=15
data[3]=5
…
…
data[98]=3
data[99]=12
.
.
.
data[0]=12
data[1]=7
data[2]=5
data[3]=15
…
…
data[98]=3
data[99]=5
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 38 38
solution
int data[100], i, j, k, tmp;
for (i=0; i<100; i++)
data[i] = (rand() % 100) + 10;
for (n=0; n<30; n++){
i= rand() % 100;
j= rand() % 100;
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
15
#include <stdio.h>
void main(void){
int count[4] = {0};
do{
int num;
scanf("%d", &num);
if(num < 0 ) break;
if(num > 5)
if(num > 7.5)
count[3]++;
else
count[2]++;
else
if(num < 2.5)
count[0]++;
else
count[1]++;
}while(1);
printf("[%d] = %d, [%d] = %d, [%d] = %d, [%d] = %d\n", 0, count[0], 1,count[1], 2, count[2], 3, count[3]);
}
با كه اعداد مجموعهاياز كه برنامهايتعداد بگيردو را ميشود تمام منفي عدد
[0, 2.5), [2.5, 5), [5, 7.5] بازههاي اعداددرآورد. بدست را [7.5, …)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 40 40
Reverse an array
6 3 1 9 7 2
0 21 3 4 5
2 7 9 1 3 6
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 41 41
Reverse an Array
void reverse(double x[], int n)
{
int i=0, j=n-1;
while (i<j) {
swap(x,i,j);
i = i + 1;
j = j - 1;}
return;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 42
int main(){int a[]= {1,2,3,4,5,6};int i;reverse(a,6);for(i=0;i<6;i++)printf("%d",a[i]);
}
void reverse(double x[], int n){
int i=0, j=n-1;while (i<j) {
swap(x,i,j);i = i + 1;j = j - 1;
}return;
}
void swap(int a[],int i, int j){int tmp;
tmp = a[i];a[i] = a[j];
a[j] = tmp;}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 44 44
Group avg
• Suppose we have a sorted array of hundred grades.
• We want to find the average of top ten, second top ten students etc.
Grade[0]
Grade[1]
….
Grade[9]
Grade[10]
…
Grade[19]
Grade[20]
…
Grade[90]
….
Grade[99]
}}
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 45 45
median()
/* values in x must be sorted ! */
double median(double x[], int n)
{
/* Declare variables. */
int k;
double median_x;
/* Determine median of
values in the array. */
k = floor(n/2);
if( n % 2 != 0)
median_x = x[k];
else
median_x = (x[k-1]+x[k])/2;
/* Return median value. */
return median_x;
}
Example:
x[]={7, 9, 15, 27, 29};n=5;median_x=15
x[]={3, 6, 7, 9};
n=4;
median_x=(6+7)/2
median_x=6.5
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 46
Initializing Variable Length arraysint n;
scanf("%d", &n);
int num[n]={0}; /* Compile error */
• Variable length arrays cannot be initialized!
• Solution
for(i = 0; i < n; i++)
num[i] = 0;
9
#include <stdio.h>
#define SIZE 20
void main(void){
int number[SIZE];
double average;
int sum, large_size, small_size, i;
}
sum = large_size = small_size = 0;
for(i = 0; i < SIZE; i++){
int tmp;
scanf("%d", &tmp);
number[i] = tmp;
sum += number[i];
}
average
for(i =
= (1.0 * sum) / SIZE;
0; i < SIZE; i++)
if(number[i] >= average)
large_size++;
else
small_size++;
printf("average = %f\n", average);
printf("Small Size = %d, Large Size = %d\n", small_size, large_size);
و بگيرد را عدد برنامهايكه20از كوچكتر و بزرگتر تعداداعداد
كند. حساب ميانگينرا
10
#include <stdio.h>
void main(void){
int n;
printf("Enter n: ", n);
scanf("%d", &n);
int number[n];
double average;
int sum, large_size, small_size, i;
}
sum = large_size = small_size = 0;
for(i = 0; i < n; i++)
scanf("%d", &(number[i]));
for(i =
sum
average
for(i =
0; i < n; i++)
+= number[i];
= (1.0 * sum) / n;
0; i < n; i++)
if(number[i] >= average)
large_size++;
else
small_size++;
printf("average = %f\n", average);
printf("Small Size = %d, Larg Size = %d\n", small_size, large_size);
رشته يك اعدادو تعداد برنامهايكهبزرگترو اعداد تعداد و بگيرد عددراكند. حساب ميانگينرا كوچكتراز
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 49
Array Elements in Functionsint number[20];
number[i] is an integer variable
Array element can be used for call by value input
Array element can be use for output
int f(int x);
void h(void){
int arr[50];
in call by value//Array element
arr[30] = f(arr[5]);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 50
Arrays in Functions (cont’d)Array cannot be used as output type of
function
int [] f(int x, int y); //compile error
Arrays can be used in input list of functions
Arrays are not passed by Call By Value
Arrays are passed by Call By Reference
If we change array elements in a function
The element is changed in the caller function
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 51
Arrays in Functions (version 1)Function arr_func takes an array of integers
int arr_func(int num[90]){
}
or
int arr_func(int num[]){
}
Array a is passed to function arr_func
int a[90];
i = arr_func(a);
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 52 52
main()
{
int a[2]={3, 5};
int c;
c = sum_arr(a, 2)
}
int sum_arr(int b[], int n)
{
int i, sum=0;
for(i=0; i < n; i++)
sum = sum + b[i];
return(sum);
}
a[0]=3
a[1]=5
c=? 8
b=
n=2
i=0 1 2
sum=0 3 8
Exercise
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 53 53
main()
{
int a[2]={3, 5};
int c;
c = sum_arr(a, 2)
}
int sum_arr(int b[], int n)
{
int i, sum=0;
for(i=0; i < n; i++)
sum = sum + b[i];
b[0] = 20;
return(sum);
}
a[0]=3 20
a[1]=5
c=? 8
b=
n=2
i=0 1 2
sum=0 3 8
Exercise
21
#include <stdio.h>
void init_array(int arr[10]){
int i;
for(i = 0; i < 10; i++)
arr[i] = i;
}
void main(void){
int a[10];
init_array(a);
int j;
for(j = 0; j < 10;
printf("a[%d] =
j++)
%d\n", j, a[j]);
}
10طولبهارايهيككهتابعيباراآناعضايوگيردميرا
.ميكندمقداردهي9تا0اعداد
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 55
Array Size in Functions
55
If array is an input parameter of a function It cannot find out the size of the array
Array size should be passed from caller function to called function Using definitions
#define SIZE 20
for(int i = 0; i < SIZE; i++)void func(int a[]){
…
Using input variablevoid read(int a[], int size){ for(int i = 0; i < size; i++)
or
void read(int size, int a[size]){
for(int i = 0; i < size; i++)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 56
Array Size in Functions (cont’d) If array is declared in a function It knows the size of the array
It can find out the size of the array using sizeof
void func(void){
int i, a[200];
for(i = 0; i < 200; i++)
a[i] = 0;
or
for(i = 0; i < sizeof(a)/sizeof(a[0]); i++)
a[i] = 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 57
27
#include <stdio.h>
int max_index(int a[], int size){
int i;
int index = 0;
for(i = 1; i < size; i++)
if(a[i] > a[index])
index = i;
return index;
}
void main(void){
int arr[] = {1, 4, 12, 93,
printf("max index = %d\n",
23};
max_index(arr, 5));
}
محل بگيردو آرايهرا ك ي كه تابعي
برگرداند. آنرا بزرگترينعضو
28
#include <stdio.h>
}
a[], int i, int j){void array_swap(int
int tmp;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void main(void){
int num[10] = {1, 2, 5, 6};
int x = 2, y = 6;
printf("num[%d] = %d, num[%d] = %d\n", x, num[x], y,
num[y]);
array_swap(num, x, y);
printf("num[%d] = %d, num[%d] = %d\n", x, num[x], y,
num[y]);
آنرا محل دو آرايهو ك ي تابعيكه
كند. جابجا باهم آنهارا بگيردو
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 59
#include <stdio.h>
a[], int i, int j){void array_swap(int
int tmp;
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void selection _sort(int a[], int size){
int i, j;
for(i = 0; i < size - 1; i++)
for(j = i + 1; j < size; j++)
if(a[i] < a[j])
array_swap(a, i, j);
}
اعدادصحيح مجموعه مرتبسازي تابع
30
void
}
print(int a[], int size){
int i;
for(i = 0; i < size; i++)
printf("%d ", a[i]);
11, 0};
sizeof(arr[0]);
printf("\n");
}
int main(void){
int arr[] = {1, 7, 3, 7,
int size = sizeof(arr) /
printf("Before sort: ");
print(arr, size);
selection_sort(arr, size);
printf("After sort: ");
print(arr, size);
return 0;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 61 61
Unordered list – linear search
int search1(int x[], int n, int value)
{
int i;
for(i=0; i < n; i++) {
if (x[i]== value)
return i;
}
return(-1);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 62 62
Ordered list – linear search
int search2(int x[], int n, int value)
{
int i;
for(i=0; i < n; i++) {
if (x[i]== value)
return i;
else if (x[i] > value)
break;
}
return(-1);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 63
Binary Searchint end, int a[], intint bsearch(int start,
value){
int mid =
if(a[mid]
return
(start + end) / 2;
== value)
mid;
>= end)else if(start
return -1;
else if(value > a[mid])
bsearch(mid + 1, end, a, value);return
else
return bsearch(start, mid - 1 , a, value);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 64
64
Bubble sort • Bubble sort Several passes through the array
– Successive pairs of elements are compared • If increasing order (or identical ), no change• If decreasing order, elements exchanged
– Repeat
• Example:– original: 3 4 2 6 7– pass 1: 3 2 4 6 7– pass 2: 2 3 4 6 7 –
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 65
/* Bubble sort code */
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of
elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 66 66
Merge two sorted array• Assume we have A and B arrays containing
sorted numbers
• For example– A = { 3, 5, 7, 9, 12}
– B = {4, 5, 10}
• Merge these two arrays as a single sorted array C, for example– C = {3, 4, 5, 5, 7, 9, 10, 12}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 67 67
Intersection Set
• Suppose we have two sets (groups) represented by A and B
• E.g., A is the set of students taking Math,
B is the set of students taking Science.
• Find set C, the intersection of A and B, i.e., students taking both Math and Science
For each element ID in A
Search that ID in B
if found, put ID into C
3 6 9 17 2
458
Use arrays to represent A and B Hand example
68
6 3 1 9 7 2A 4 2 5 6 1 8B
6 1 2C
i=0 j=0
k=0
j=1 j=3
k=1
i=1j=2
k=2
i=2
i=3
k=3
j=0 j=1 j=2 j=3 j=4 j=5 j=6
j=0 j=1 j=2 j=3 j=4i=4 i=5 i=6
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 69 69
int intersection(int A[],int B[],
int C[], int n)
{
int i=0, j=0, k=0;
for(i=0; i < n; i++) {
for(j=0; j < n; j++) {
if (A[i]==B[j]){
C[k]=A[i];
k++;
break;
}
}
}
return(k);
}
Solution
6 3 1 9 7 2
4 2 5 6 1 8
6 1 2
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 70
Multidimensional Arrays• Arrays in C can have virtually as many dimensions as you
want• Definition is accomplished by adding additional subscripts
when it is defined• If element of an array is array itself, it will be
Multidimensional array• For example:
– int a [4] [3] ;• 2-dimensional array• 4 * 3 * sizeof(int)
– int a[4][3][2]• 3-dimention array• 4 * 3 * 2 * sizeof(int)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 71
Multidimensional Arrays Representation
Row 0Row 1Row 2
Column 0 Column 1 Column 2 Column 3
a[ 0 ][ 0 ]
a[ 1 ][ 0 ]
a[ 2 ][ 0 ]
a[ 0 ][ 1 ]
a[ 1 ][ 1 ]
a[ 2 ][ 1 ]
a[ 0 ][ 2 ]
a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 3 ]
a[ 2 ][ 3 ]
Row subscript
Array name
Column subscript
a[0][0]
a[0][1]
a[0][2]
a[0][3]
a[1][0]
a[1][1]
a[1][2]
a[1][3]
a[2][0]
a[2][1]
a[2][2]
a[2][3]
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 72
Examples• Initialization
– Example:
• short b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– If not enough, unspecified elements set to zero
• short b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
21
43
01
43
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 73
Initializing Multidimensional Arrays• The following initializes a[4][3]:
int a[4] [3] = { {1, 2, 3} , {4, 5, 6} , {7, 8, 9} ,{10, 11, 12} };
• Also can be done by:int a[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
– is equivalent toa[0][0] = 1;a[0][1] = 2;a[0][2] = 3;a[1][0] = 4;...a[3][2] = 12;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 74
Multidimensional Arraysint t[10][20];
10x20 matrix of integers
t[1][1]; //t[1,1] compile error
Integer variable in location (1,1)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 75
Initializing Multidimensional Arraysint num[2][3]
int num[2][3]
= {1, 2, 0, 3, 4
= {{1, 2, 0},{3,
, 7};
4, 7}};
num[0][2] is ?, num[1][0] is ?
int num[2][3][2] = {{{1,2},{3,4},{5,6}},{{1},{2},{3}}};
num[0][2][1] is ?, num[1][0][1] is ?
int num[5][3] = {{1, 2,0},{3, 4, 7}};
num[0][2] is 0, num[1][0] is 3
num[2][2] is 0, num[1][2] is 7 num[2][2] is ?, num[1][2] is ?
num[1][1] is 2, num[2][0] is 3
num[0][2][1] is 6, num[1][0][1] is 0
int num[][2] = {{1,1},{2,2},{3,3}};
num[1][1] is ?, num[2][0] is ?
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 77
Initialization
int i, j, matrix[3][4];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
matrix[i][j] = i;j
0 1 2 3
0
1
2
i
0 0 0 0
1 1 1 1
2 2 2 2
j
0 1 2 3
0
1
2
i
0 1 2 3
0 1 2 3
0 1 2 3
matrix[i][j] = j;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 78 78
Exercise
0 1 2
1 2 3
2 3 4
3 4 5
• Write the nested loop to initialize a 2D array as follow
int i, j, x[4][3];
for(i=0; i<4; i++)
for(j=0; j<3; j++)
x[i][j] = i+j;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 79
An Example#include <stdio.h>#include <stdlib.h>int main () {
int random1[10][8];int a, b;for (a = 0; a < 10; a++)
for (b = 0; b < 8; b++)random1[a][b] = rand() % 2;
for (a = 0; a < 10; a++){
for (b = 0; b < 8; b++)printf ("%c ", random1[a][b] ? 'x' : 'o');
printf("\n");}
return 0; }
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 80
Multidimensional Arrays in FunctionsCan be used as input of functions
All dimensions except the first one must be given
void func(int a[10][20][5]);
Input is a 10x20x5 integer matrix
void func(int a[][20][30], int size);
void func(int size1, int size2, int
a[size1][size2]);
Input is a matrix of integers that both rows and columns are variable
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 81
Multidimensional Arrays in FunctionsThe first subscript therefore only indicates the amount of storage that is needed when the array is declared
Others are required because the computer needs to know how far along to increment the pointer for each "row"
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 82
37
#include <stdio.h>
}
void displayMatrix (int nRows, int nCols, int matrix[nRows][nCols]){
int row, column;
for ( row = 0; row < nRows; ++row) {
0; column < nCols; ++column )
matrix[row][column]);
for ( column =
printf ("%5i",
printf ("\n");
}
}
7 }, { -2, 1,
int main (void){
int sampleMatrix[3][5] =
{{ 7, 16, 55, 13, 12 }, { 12, 10, 52, 0,
2, 4, 9 }};
printf ("Original matrix:\n");
displayMatrix (3, 5, sampleMatrix);
ماتريس ك ي برايچاپ تابعي
#define
}
SIZE 5
void swap(int a[SIZE][SIZE], int i, int j){
int tmp;
tmp = a[i][j];
a[i][j]
a[j][i]
= a[j][i];
= tmp;
}
void transpose(int a[][SIZE]){
for(i =
int i, j;
0; i < SIZE; i++)
for(j = i; j < SIZE; j++)
swap(a, i, j);
ماتريس ترانهاده محاسبه// Matrix Transpose
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 84 84
2-Dim Arrays as Arguments to Functions
void print_m(int m[][4], int r, int c)
{
int i,j;
for (i=0; i < r; i++) {
for (j=0; j < c; j++)
printf("%.5d ",m[i][j]);
printf("\n");
}
printf("\n");
return;
}
int i, j, matrix[3][4];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
matrix[i][j] = i;
print_m(matrix, 3, 4);
void print_m(int m[3][4], int r, int c)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 85
Matrix sum
• Compute the addition of two matrices
3 0 33
0 6 6 3
2 0 4 4
0 1 2 3
0
1
2
0 1 20
-1 2 4 3
0 -1 3 1
0
1
2
0 1 2 3
+
3 -1 13
1 4 2 0
2 1 1 3
0
1
2
0 1 2 3
=
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 86 86
solution
int matrix1[3][4],
matrix2[3][4],
sum[3][4];
// initialize matrix1 and matrix2
for (i=0; i<3; i++)
for (j=0; j<4; j++)
sum[i][j]= matrix1[i][j]+matrix2[i][j];
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 88 88
Transpose
void transpose(int a[NROWS][NCOLS],
int b[NCOLS][NROWS])
{
/* Declare Variables. */
int i, j;
/* Transfer values to the
transpose matrix. */
for(i=0; i<NROWS; i++) {
for(j=0; j<NCOLS; j++) {
b[j][i] = a[i][j];
}
}
return;
}
1 5 3
4 2 6
1 4
5 2
3 6
b
a
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 89
89
Matrix multiplication
double a[3][2], b[2][4], c[3][4];
• Find c = a * b;
x =
3*2 + 4*4=22 3*3 + 4*5=29
2 3 7 1
4 5 6 8
3 4
5 2
1 6
22 29 45 35
18 40 47 21
26 33 43 49
5*2 + 2*4=18
3*7 + 4*6=45 3*1 + 4*8=35
5*3 + 2*5=40 5*7 + 2*6=47 5*1 + 2*8=21
1*2 + 6*4=26 1*3 + 6*5=33 1*7 + 6*6=43 1*1 + 6*8=49
90
Matrix Multiplication cont’d
x =2 3 7 1
4 5 6 8
3 4
5 2
1 6
22 29 45 35
18 40 47 21
26 33 43 49
i=0
i
jj
3 42
4x
j=0
k
k =
c[i][j] =
a[i][k=0]*b[k=0][j] +
a[i][k=1]*b[k=1][j]
0 1 2 3
i
0
1
2
0 1 2 3
0
1
2
91
Matrix Multiplication cont’d
#define N 3
#define M 2
#define L 4
void matrix_mul(a[N][M], int b[M][L], int c[N][L])
{
int i, j, k;
for(i=0; i < N; i++) {
for(j=0; j < L; j++) {
c[i][j] = 0;
for(k=0; k < M; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 92
Common Bugs & Avoiding them You cannot assign a value to array
int a[4], b[4]; a = b; // Error
Each array name refers to a constant
pointer.
Can’t change where the array name
refers to
But you can change the array elements,
via pointer arithmetic
(int [])
m
???(int)
???(int)
???(int)
???(int)
int m[4];